简体   繁体   English

从列表中删除相等的元素

[英]Deleting equal elements from a list

Can I check out if one single list has two or more equal elements and then delete them, even if I don't know what specific elements I'm looking for ? 即使我不知道要查找的特定元素,我是否可以检查一个列表是否包含两个或更多个相等的元素,然后将其删除?

Or check the different elements when comparing two lists, like AB, in set theory. 或在集合论中比较两个列表(例如AB)时检查不同的元素。 Getting elements in A that doesn't exist in B. 在A中获取B中不存在的元素。

If you don't care about the order of the items, just use the Python set data type instead of lists: 如果您不关心项目的顺序,只需使用Python set数据类型而不是列表即可:

s = set([1, 2, 3, 3])
t = set([2, 4, 6])
print s
print t
print s - t

prints 版画

set([1, 2, 3])
set([2, 4, 6])
set([1, 3])

For the Or check ... part of your questions: 对于您的问题的“ Or check ...部分:

In []: A, B= {1, 2, 3, 4}, {2, 4, 6, 8}
In []: A- B
Out[]: set([1, 3])

Update concerning the validity of used syntax: 关于所用语法的有效性的更新

In []: A, B= {1, 2, 3, 4}, {2, 4, 6, 8} # seems to be valid for 2.7 and above
# In []: A, B= set([1, 2, 3, 4]), set([2, 4, 6, 8]) # for 2.4 and above
In []: A- B # apparently since 2.4
Out[]: set([1, 3])

There's an actual set builtin type that allows you to do things like intersection() and union() , but if you're dealing with a simple list and want the unique version of it, a fast and simple way of doing it is simply inserting them into a dictionary and taking the keys once you're done. 有一个实际的内置set类型,它允许您执行诸如intersection()union() ,但是如果您要处理一个简单的列表并想要它的唯一版本,那么一种快速简便的方法就是插入将它们放入字典中,并在完成后获取密钥。

>>> L = [1, 2, 2, 3, 3, 3, 4, 5, 6, 6]
>>> d = {}
>>> for num in L:
    d[num] = None


>>> d.keys()
[1, 2, 3, 4, 5, 6]

And if you're interested in order-preserving, then there's an interesting blog post exploring various ways of "uniquifying" a list both with and without order preservation here . 如果你感兴趣的保序,然后还有一个有趣的博客文章探索“uniquifying”列表既没有为了保存各种方式在这里

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

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