一文看懂Python中的集合运算&,|,-,^

本是古典 何须时尚 2023-03-14 13:59 11923阅读 0赞

关于集合的概念

Python 中常用的集合方法是执行标准的数学运算,例如:求并集、交集、差集以及对称差。下图显示了一些在集合 A 和集合 B 上进行的标准数学运算。每个韦恩(Venn)图中的红色部分是给定集合运算得到的结果。
在这里插入图片描述

Python中相应符号:

  • &符号在Python中既可以执行通常的按位与运算,也可以执行set集合里面的交集运算
  • |:并集;也可以表示数字运算中的按位或运算
  • -:差集
  • ^:对称差集

举例

  1. pre = ["berry","grape","pea_r","apple","banana","pear"]
  2. pos = ["apple","banana","pear","potato","cucumber"]
  3. pre_set = set(pre) # 转换list为集合set
  4. pos_set = set(pos)
  5. union = pos_set | pre_set # 并集
  6. print('The union of the two sets above is:\n{}\n'.format(union))
  7. intersection = pos_set & pre_set # 交集
  8. print('The intersection of two sets is:\n{}\n'.format(intersection))
  9. only_in_preset = pre_set - pos_set # 差集
  10. print('The unique part in pre_set is:\n{}\n'.format(only_in_preset))
  11. only_in_posset = pos_set - pre_set # 差集
  12. print('The unique part in pos_set is:\n{}\n'.format(only_in_posset))
  13. sym_set_diff = pos_set^pre_set # 对称差集
  14. print('The symmetric set difference of the two sets is:\n{}'.format(sym_set_diff))

输出结果如下:

  1. The union of the two sets above is:
  2. {'potato', 'grape', 'banana', 'pear', 'berry', 'pea_r', 'cucumber', 'apple'}
  3. The intersection of two sets is:
  4. {'pear', 'apple', 'banana'}
  5. The unique part in pre_set is:
  6. {'berry', 'grape', 'pea_r'}
  7. The unique part in pos_set is:
  8. {'potato', 'cucumber'}
  9. The symmetric set difference of the two sets is:
  10. {'potato', 'pea_r', 'berry', 'cucumber', 'grape'}

发表评论

表情:
评论列表 (有 0 条评论,11923人围观)

还没有评论,来说两句吧...

相关阅读

    相关 网络模型

    各层 应用层 各个应用(比如:www、邮件、文件服务)使用什么协议,协议的原理,完成业务处理部分。 协议有:HTTP、HTTPS、FTP、DNS(域名服务) 等

    相关 Mysql事务

    MySQL 事务 本文所说的 MySQL 事务都是指在 InnoDB 引擎下,MyISAM 引擎是不支持事务的。 数据库事务指的是一组数据操作,事务内的操作要么就是全部