python删除所有重复的内容

时间:2019-09-28 16:19:48

标签: python

input: [1,1,2,2,3,3,4,5,5,6,6]

output: 4

尝试,设置并形成新列表,但无法弄清楚如何消除所有重复元素,包括元素本身。

3 个答案:

答案 0 :(得分:2)

my_list = [1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6]
filtered_list = [value for value in my_list if my_list.count(value) == 1]
print(filtered_list)
[4]

答案 1 :(得分:2)

这是使用collections.Counter

的一种方法。
>>> from collections import Counter
>>> inp = [1,1,2,2,3,3,4,5,5,6,6]
>>> counted_inp = Counter(inp)
>>> counted_inp
Counter({1: 2, 2: 2, 3: 2, 5: 2, 6: 2, 4: 1})
>>> [inp_item for inp_item, inp_count in counted_inp.items() if inp_count == 1]
[4]

文档:https://docs.python.org/3.7/library/collections.html#collections.Counter

答案 2 :(得分:1)

您可以使用filter()

inp = [1,1,2,2,3,3,4,5,5,6,6]
res = list(filter(lambda x: inp.count(x) == 1, inp))  # list() isn't necessary for python 2