集合(无序数据,优化逻辑运算)

Python 的数据类型

Jason Myers

Instructor

集合

  • 唯一
  • 无序
  • 可变
  • Python 对数学集合论的实现
Python 的数据类型

创建集合

  • 可由列表创建集合
cookies_eaten_today = ['chocolate chip', 'peanut butter', 
   ...: 'chocolate chip', 'oatmeal cream', 'chocolate chip']

types_of_cookies_eaten = set(cookies_eaten_today)
print(types_of_cookies_eaten)
set(['chocolate chip', 'oatmeal cream', 'peanut butter'])
Python 的数据类型

修改集合

  • .add() 添加单个元素
types_of_cookies_eaten.add('biscotti')

types_of_cookies_eaten.add('chocolate chip')

print(types_of_cookies_eaten)
set(['chocolate chip', 'oatmeal cream', 'peanut butter', 'biscotti'])
Python 的数据类型

更新集合

  • .update() 合并另一个集合或列表
cookies_hugo_ate = ['chocolate chip', 'anzac']

types_of_cookies_eaten.update(cookies_hugo_ate)

print(types_of_cookies_eaten)
set(['chocolate chip', 'anzac', 'oatmeal cream',  'peanut butter', 'biscotti'])
Python 的数据类型

从集合中删除数据

  • .discard() 按值安全移除元素
  • .pop() 移除并返回任意元素(为空时 KeyError)
types_of_cookies_eaten.discard('biscotti')

print(types_of_cookies_eaten)
set(['chocolate chip', 'anzac', 'oatmeal cream', 'peanut butter'])
types_of_cookies_eaten.pop()
types_of_cookies_eaten.pop()
'chocolate chip'
'anzac'
Python 的数据类型

集合运算——相同部分

  • .union() 返回两个集合的所有元素("或")
  • .intersection() 找到重叠数据("与")
cookies_jason_ate = set(['chocolate chip', 'oatmeal cream',
'peanut butter'])
cookies_hugo_ate = set(['chocolate chip', 'anzac'])

cookies_jason_ate.union(cookies_hugo_ate)
set(['chocolate chip', 'anzac', 'oatmeal cream', 'peanut butter'])
cookies_jason_ate.intersection(cookies_hugo_ate)
set(['chocolate chip'])
Python 的数据类型

集合运算——差异

  • .difference() 找到在调用者集合中但不在参数中的数据("-")
  • 目标(调用者)很重要!
cookies_jason_ate.difference(cookies_hugo_ate)
set(['oatmeal cream', 'peanut butter'])
cookies_hugo_ate.difference(cookies_jason_ate)
set(['anzac'])
Python 的数据类型

Passons à la pratique !

Python 的数据类型

Preparing Video For Download...