python - 删除 Python 列表列表中的重复项

标签 python python-2.7 list

基本上,我试图删除所有以相同值开头的列表。例如,以下两个以数字 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/

相关文章:

python - 导入尚不存在的模块

python - 通过python向表中插入记录

python - 从列表中查找需要多少个元素才能达到一定的覆盖率

python - 回文函数在 Python 中不起作用

python - 如何将 float 转换为十六进制

c - 用c编写的listSort函数工作错误

python - 如何在 Python 中创建用户定义的列表?

python - 当 Variable 的第一个维度为 None 时使用 tf.unpack()

python - 使用 subprocess.Popen() 或 subprocess.check_call() 时程序卡住

c# - 将对对象的引用添加到列表