基本上,我试图删除所有以相同值开头的列表。例如,以下两个以数字 1 开头:
a = [[1,2],[1,0],[2,4],[3,5]]
因为值 1 存在于两个列表的开头 - 我需要删除两个列表以便新列表变为:
b = [[2,4],[3,5]]
我该怎么做?
我试过下面的方法,但输出是:[[1, 2], [2, 4], [3, 5]]
def unique_by_first_n(n, coll):
seen = set()
for item in coll:
compare = tuple(item[:n])
print compare # Keep only the first `n` elements in the set
if compare not in seen:
seen.add(compare)
yield item
a = [[1,2],[1,0],[2,4],[3,5]]
filtered_list = list(unique_by_first_n(1, a))
最佳答案
一个有效的解决方案是创建一个 Counter
对象保存第一个元素的出现,然后过滤主列表中的子列表:
from collections import Counter
counts = Counter(l[0] for l in a)
filtered = [l for l in a if counts[l[0]] == 1]
#[[2, 4], [3, 5]]
关于python - 删除 Python 列表列表中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52029529/