简体   繁体   English

python 从元组列表中删除 tup[0] 重复项

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

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

I want to remove the tup[0] duplicates ("abc", 6) and ("ghi", 5) from the list, so the output should be:我想从列表中删除 tup[0] 重复项("abc", 6)("ghi", 5) ,因此 output 应该是:

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

How do I do this?我该怎么做呢?

There are more elegant solutions, but this worked.有更优雅的解决方案,但这很有效。

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 output

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

Just use a set to keep track of the first items youv'e already seen:只需使用一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