繁体   English   中英

python 删除所有重复项包括该元素

[英]python remove all duplicates include that elements

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

output: 4

尝试,设置,形成新列表,但无法弄清楚如何摆脱包括元素本身在内的所有重复项。

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]

这是一种方法,使用 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

您可以使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM