set 集合数据类型

set 数据类型

  • set 与列表类似,区别在于 set 不能包含重复的值。
In [1]: a_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']

In [2]: b = set(a_list)

In [3]: b
Out[3]: {'a', 'b', 'c', 'd', 'm', 'n'}

In [4]: type(b)
Out[4]: set
  • set 获取重复的元素
In [7]: a_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']

In [8]: b = set([i for i in a_list if a_list.count(i) > 1])

In [9]: b
Out[9]: {'b', 'n'}
  • set 为集合,集合可取交集,集合运算很快,性能很好
In [10]: a_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']

In [11]: b_list = ['a', 'c']

In [12]: c = set(a_list).intersection(set(b_list))

In [13]: c
Out[13]: {'a', 'c'}

set 类型调用 intersection 取2个集合的交集

  • set 为集合,集合可取差集,集合运算很快,性能很好
In [20]: a_set = set(['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n'])

In [21]:  b_set = set(['a', 'c', 'f', 'g'])

In [22]: b_set.difference(a_set)
Out[22]: {'f', 'g'}

set 类型调用 difference, 获取元素在 b_set 不在 a_set 的数据

posted @ 2018-10-19 11:06  深圳-随风  阅读(906)  评论(0编辑  收藏  举报