簡體   English   中英

python 從元組列表中刪除 tup[0] 重復項

[英]python remove tup[0] duplicates from list of tuples

input = [("abc", 2), ("def", 7), ("abc", 6), ("ghi", 2), ("ghi", 5)]

我想從列表中刪除 tup[0] 重復項("abc", 6)("ghi", 5) ,因此 output 應該是:

output = [("abc", 2), ("def", 7), ("ghi", 2)]

我該怎么做呢?

有更優雅的解決方案,但這很有效。

input = [("abc", 2), ("def", 7), ("abc", 6), ("ghi", 2), ("ghi", 5)]

output = []
first_tups = []

for tup in input:
    if tup[0] not in first_tups:
        output.append(tup)
        first_tups.append(tup[0])

print(output)

output

[('abc', 2), ('def', 7), ('ghi', 2)]

只需使用一set來跟蹤您已經看到的第一個項目:

>>> input_data = [("abc", 2), ("def", 7), ("abc", 6), ("ghi", 2), ("ghi", 5)]
>>> seen = set()
>>> result = []
>>> for tup in input_data:
...     s = tup[0]
...     if s not in seen:
...         seen.add(s)
...         result.append(tup)
...
>>> result
[('abc', 2), ('def', 7), ('ghi', 2)]

暫無
暫無

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

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