[英]Python remove list with duplicated fields in a list of lists
当列表中的字段在 python3 中重复时,我希望能够从列表列表中删除一个元素。
IE:
当第二个字段重复时,从以下列表列表中删除。 从
[["John","France"], ["Mike", "France"], ["Ana","Italy"]]
到
[["John","France"], ["Ana","Italy"]]
编辑:我已经尝试了以下循环,但我期待着一种更有效的方法,如果它存在的话。
for element in consult_array:
for other_elements in consult_array:
if element[1] == other_elements[1]:
if element != other_elements:
consult_array.pop(element)
data = [["John", "France"], ["Mike", "France"], ["Ana", "Italy"]]
output = []
already_seen_countries = set()
for item in data:
country = item[1]
if country not in already_seen_countries:
output.append(item)
already_seen_countries.add(country)
print(output) # [['John', 'France'], ['Ana', 'Italy']]
如果您喜欢单行解决方案:
l = [["John","France"], ["Mike", "France"], ["Ana","Italy"]]
list(t for t in {e[1]: e for e in l[::-1]}.values())[::-1]
输出:
[['John', 'France'], ['Ana', 'Italy']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.