博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 集合(set)基础
阅读量:5032 次
发布时间:2019-06-12

本文共 2087 字,大约阅读时间需要 6 分钟。

1、定义

list_1 = [1,4,5,7,3,6,7,9]list_1 = set(list_1)list_2 =set([2,6,0,66,22,8,4])print(list_1,list_2)

  打印输出结果:

{1, 3, 4, 5, 6, 7, 9} {0, 2, 66, 4, 6, 8, 22}

 

2、交集

list_1 = [1,4,5,7,3,6,7,9]list_1 = set(list_1)list_2 =set([2,6,0,66,22,8,4])print(  list_1.intersection(list_2) )print(list_1 & list_2)

  打印输出结果:

{4, 6}{
4, 6}

 

3、并集

list_1 = [1,4,5,7,3,6,7,9]list_1 = set(list_1)list_2 =set([2,6,0,66,22,8,4])print(list_1.union(list_2))print(list_1 | list_2)

   打印输出结果:

{0, 1, 2, 3, 4, 5, 6, 7, 66, 9, 8, 22}{0, 1, 2, 3, 4, 5, 6, 7, 66, 9, 8, 22}

 

4、 差集 in list_1 but not in list_2

list_1 = [1,4,5,7,3,6,7,9]list_1 = set(list_1)list_2 =set([2,6,0,66,22,8,4])print(list_1.difference(list_2))print(list_1 - list_2)

  打印输出结果:

{1, 3, 5, 7, 9}{
1, 3, 5, 7, 9}

 

5、差集 in list_2 but not in list_1

list_1 = [1,4,5,7,3,6,7,9]list_1 = set(list_1)list_2 =set([2,6,0,66,22,8,4])print(list_2.difference(list_1))print(list_2 - list_1)

  打印输出结果:

{0, 2, 66, 8, 22}{0, 2, 66, 8, 22}

 

6、子集

list_1 = [1,4,5,7,3,6,7,9]list_1 = set(list_1)list_3 = set([1,3,7])print(list_3.issubset(list_1))

  打印输出结果:

True

 

7、超集

list_1 = [1,4,5,7,3,6,7,9]list_1 = set(list_1)list_3 = set([1,3,7])print(list_1.issuperset(list_3))

  打印输出结果:

True

 

8、对称差集

list_1 = [1,4,5,7,3,6,7,9]list_1 = set(list_1)list_2 =set([2,6,0,66,22,8,4])print(list_1.symmetric_difference(list_2))print(list_1 ^ list_2)

  打印输出结果:

{0, 1, 2, 66, 3, 5, 7, 8, 9, 22}{0, 1, 2, 66, 3, 5, 7, 8, 9, 22}

 

9、判断是否有相同项,没有则返回true

list_3 = set([1,3,7])list_4 = set([5,6,7,8])print(list_3.isdisjoint(list_4))

  打印输出结果:

False

 

10、add()与update

list_1 = [1,4,5,7,3,6,7,9]list_1 = set(list_1)list_1.add(999)list_1.update([888, 777, 555])print(list_1)

 

   打印输出结果:

{1, 3, 4, 5, 6, 7, 999, 9, 777, 555, 888}

 

11、pop()

list_1 = [1,4,5,7,3,6,7,9]list_1 = set(list_1)print(list_1.pop())print(list_1.pop())print(list_1.pop())print(list_1.pop())print(list_1)

  打印输出结果:

1345{
6, 7, 9}

 

12、discard()

list_1 = [1,4,5,7,3,6,7,9,888]list_1 = set(list_1)print(  list_1.discard(888)  )print(list_1)

  打印输出结果:

None{
1, 3, 4, 5, 6, 7, 9}

 

转载于:https://www.cnblogs.com/bad-robot/p/9679351.html

你可能感兴趣的文章
编写一个函数isMerge,判断一个字符串str是否可以由其他两个字符串part1和part2“组合”而成...
查看>>
PMD使用提醒
查看>>
Codeforces 887D Ratings and Reality Shows
查看>>
论文《A Generative Entity-Mention Model for Linking Entities with Knowledge Base》
查看>>
Linux记录-salt分析
查看>>
Android Studio默认快捷键
查看>>
函数式编程与参数
查看>>
SSAS使用MDX生成脱机的多维数据集CUB文件
查看>>
HDU 2191 【多重背包】
查看>>
51nod 1433 0和5【数论/九余定理】
查看>>
less 分页显示文件内容
查看>>
如何对数据按某列进行分层处理
查看>>
[Qt] this application failed to start because it could not find or load the Qt platform plugin
查看>>
Git Submodule管理项目子模块
查看>>
学会和同事相处的30原则
查看>>
文件操作
查看>>
jquery基本选择器
查看>>
hdu 1010 dfs搜索
查看>>
搭建wamp环境,数据库基础知识
查看>>
android中DatePicker和TimePicker的使用
查看>>