栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python学习日记 字典实例&集合基础操作

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python学习日记 字典实例&集合基础操作

2022.07.14 DAY14 1. 实例 1. 表格
# 创建表格
def createTable():
    staff1 = {'name': 'YJP', 'age': 21, 'city': '北京', 'job': 'Engineer'}
    staff2 = {'name': 'XX', 'age': 20, 'city': '上海', 'job': 'Engineer'}
    staff3 = {'name': 'ZHJ', 'age': 26, 'city': '上海', 'job': 'AI'}
    table = [staff1, staff2, staff3]

    # 获得第二行的人的name
    print("获得第二行的人的name:")
    print(table[1].get('name'))

    # 打印表中所有的年龄
    print("打印表中所有的年龄:")
    for i in range(len(table)):  # i --> 0, 1, 2
        print(table[i].get('age'))

    # 打印表的所有数据
    print("打印表的所有数据:")
    for i in range(len(table)):
        print(table[i].get('name'), table[i].get('age'), table[i].get('city'), table[i].get('job'))


# Main
if __name__ == '__main__':
    createTable()
2. 字典核心底层原理 1. 字典对象的核心是散列表
  • 散列表是一个稀疏数组(总是有空白元素的数组),数组的每个单元叫做bucket。

  • 每个bucket又有两个部分:一个是键对象的引用,一个是值对象的引用。

  • 哈希函数 存 取

  • 总结:

    1. 键必须可以散列。
      • 数字、字符串、元组,都是可散列的。
      • 自定义对象需要支持下面三点:
        • 支持hash函数;
        • 支持通过__eq__()方法检测相等性;
        • 若a==b为真,则hash(a)==hash(b)也为真。
    2. 字典在内存中开销巨大,典型的空间换时间。
    3. 字典查询熟读很快。
    4. 往字典里面添加新建可能导致扩容,导致散列表中的次序变化。因此,不要在遍历字典的同时进行字典的修改。
3. 集合
  • 集合是无需可变,元素不能重复。实际上,集合底层是字典实现,集合的所有元素都是字典中的"键对象",因此是不能重复且唯一的。
1. 集合的创建和删除
  • 使用{}创建集合毛病使用add()方法添加元素

      # 使用 {} 创建集合
      def test():
          mySet = {10, 20, 30}
          print(mySet)
          mySet.add(520)
          print(mySet)
    
    
      # Main
      if __name__ == '__main__':
          test()
    
  • 使用set(),经列表、元组等可迭代对象转成集合。如果原来的数据存在重复,则值保留一个。

      # 使用 set() 创建集合
      def test2():
          a = ['a', 'b', 'c', 'd']
          mySet = set(a)
          print(mySet)
    
    
      # Main
      if __name__ == '__main__':
          test2()
    
  • remove删除指定元素,clear()清空整个集合

      mySet = {10, 20, 30}
      mySet.remove(20)  # 删除指定元素
      mySet.clear()  # 清空
    
2. 集合的相关操作
  • Python对集合提供了并集、交集、差集等运算。

      # 集合的运算
      def test3():
          mySet = {'embedded', 'vue', 'nature', 'space'}
          print(mySet)
          herSet = {'web', 'vue', 'others'}
          print(herSet)
    
          # 并集
          print(mySet | herSet)
          print(mySet.union(herSet))
    
          # 交集
          print(mySet & herSet)
          print(mySet.intersection(herSet))
    
          # 差集
          print(mySet - herSet)
          print(mySet.difference(herSet))
    
    
      # Main
      if __name__ == '__main__':
          test3()
    
暑期编程PK赛 得CSDN机械键盘等精美礼品!
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1015097.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号