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 tw开发者_Go百科o lists, like A-B, in set theory. Getting elements in A that doesn't exist in B.
If you don't care about the order of the items, just use the Python set
data type instead of lists:
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:
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.
>>> 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.
精彩评论