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 的数据

相关文章:

  • 2021-11-23
  • 2021-04-07
  • 2021-06-02
  • 2021-11-02
  • 2022-12-23
  • 2022-12-23
  • 2021-10-10
  • 2021-04-29
猜你喜欢
  • 2021-10-11
  • 2021-10-20
  • 2021-09-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案