Python添加两个集合并删除重复的元素

时间:2018-03-12 03:44:00

标签: python python-2.7

如何添加两个集并删除重复项

list = [
    [1, 2, 4, 5],
    [2, 3, 4, 5],
    [1, 3, 4, 5, 6],
    [1, 2, 3],
]

tmp = {}
for item_list in list:
    for item in item_list:
        if str(item) in tmp.keys():
            tmp[str(item)] += 1
        else:
            tmp[str(item)] = 1

print(tmp)

4 个答案:

答案 0 :(得分:1)

您可以使用逻辑或运算符|

来获取两个集合的并集
a = set(['a', 'b', 'c'])
b = set(['c', 'd', 'e'])
c = a | b

print(c)
  

{&#39; e&#39;&#39; a&#39;,&#39; b&#39;,&#39; d&#39;,&#39; c&#39;} < / p>

如果您想要有序的集合并作为列表

c = sorted(list(c))
print(c)
  

[&#39; a&#39;,&#39; b&#39;,&#39; c&#39;,&#39; d&#39;,&#39; e&#39;] < / p>

答案 1 :(得分:1)

试试这个:

>>> a = set(['a', 'b', 'c'])
>>> b = set(['c', 'd', 'e'])
>>> c = a.union(b)

结果:

  

set(['a','b','c', 'd', 'e'])

答案 2 :(得分:0)

使用union方法

您想要使用集合的union方法:

c = a.union(b)

https://docs.python.org/2/library/stdtypes.html#frozenset.union https://docs.python.org/3/library/stdtypes.html?highlight=sets#frozenset.union

union方法与|运算符相同,因此上面的代码行相当于

c = a | b

使用就地操作员

如果您不需要保留ab,最好使用update方法,这将添加新成员。也就是说,

a.update(b)

将在现有数据结构a中生成联合。这也是由等效代码

执行的
a |= b

旁注:使用set字面值

在您提供的代码中,使用{element, element, ...}设置的文字表示法会更快:

a = {'a', 'b', 'c'}

因为它的执行速度会快两倍而不会生成未使用的列表对象。

答案 3 :(得分:-1)

c = set(set(list(a) + list(b))

set()返回<str set>所以无法将两个集合添加到一起

https://docs.python.org/2/library/sets.html

相关问题