[英]List of unique items in a list of tuples
I have a list of tuples like this: mylist = [(1,2,3),(6,1,1),(7,8,1),(3,4,5)]
. 我有一个像这样的元组列表:
mylist = [(1,2,3),(6,1,1),(7,8,1),(3,4,5)]
。 If I use the list comprehension slist = [item for sublist in mylist for item in sublist]
, I could get slist = [1,2,3,6,1,1,7,8,1,3,4,5]
. 如果我使用list comprehension
slist = [item for sublist in mylist for item in sublist]
,我可以得到slist = [1,2,3,6,1,1,7,8,1,3,4,5]
。
How should I modify if I need only unique elements in slist
like this [1,2,3,6,7,8,4,5]
? 如果我只需要像
[1,2,3,6,7,8,4,5]
这样的slist
唯一元素,我该如何修改?
Use a set instead of a list. 使用集而不是列表。
set(slist)
If you really need it as a list then you can convert it back to a list: 如果您确实需要它作为列表,那么您可以将其转换回列表:
slist = list(set(slist))
Note that this conversion won't preserve the original order of the elements. 请注意,此转换不会保留元素的原始顺序。 If you need the same order you can use this instead:
如果您需要相同的订单,您可以使用它:
>>> result = []
>>> seen = set()
>>> for innerlist in mylist:
for item in innerlist:
if not item in seen:
seen.add(item)
result.append(item)
>>> result
[1, 2, 3, 6, 7, 8, 4, 5]
You can actually make your first part a bit easier by using itertools.chain.from_iterable and then passing the result to set , which will only retain the unique elements: 通过使用itertools.chain.from_iterable然后将结果传递给set ,您实际上可以使您的第一部分更容易,这将只保留唯一元素:
>>> mylist = [(1,2,3),(6,1,1),(7,8,1),(3,4,5)]
>>> import itertools
>>> set(itertools.chain.from_iterable(mylist))
set([1, 2, 3, 4, 5, 6, 7, 8])
import itertools
chain = itertools.chain(*mylist)
print(set(chain))
taken from Flattening a shallow list in Python and adapted for use in this question. 摘自在Python中展平浅表并适用于此问题。
You should use python sets http://docs.python.org/library/sets.html 你应该使用python sets http://docs.python.org/library/sets.html
set(yourlist)
it will do the trick 它会做的伎俩
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.