簡體   English   中英

從List,Python中獲取獨特的元組

[英]Get Unique Tuples from List , Python

>>> a= ('one', 'a')
>>> b = ('two', 'b')
>>> c = ('three', 'a')
>>> l = [a, b, c]
>>> l
[('one', 'a'), ('two', 'b'), ('three', 'a')]

如何僅使用唯一的第二個條目(列?項?)檢查此列表的元素,然后獲取列表中的第一個條目。 期望的輸出是

>>> l
[('one', 'a'), ('two', 'b')]

使用一個集合(如果第二個項目是可散列的):

>>> lis = [('one', 'a'), ('two', 'b'), ('three', 'a')]
>>> seen = set()
>>> [item for item in lis if item[1] not in seen and not seen.add(item[1])]
[('one', 'a'), ('two', 'b')]

上面的代碼相當於:

>>> seen = set()
>>> ans = []
for item in lis:
    if item[1] not in seen:
        ans.append(item)
        seen.add(item[1])
...         
>>> ans
[('one', 'a'), ('two', 'b')]

如果訂單不重要,您可以使用字典:

d = {}

for t in reversed(l):
    d[t[1]] = t

print d.values()

或者更簡潔:

{t[1]: t for t in reversed(l)}.values()

如果你不反轉列表, ('three', 'a')將覆蓋('one', 'a')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM