在Python中比较`list`

2 投票
5 回答
923 浏览
提问于 2025-04-16 11:37

我有很多个列表。我想找个方法,生成每个列表中和其他所有列表相比的独特项目,也就是那些在其他列表里没有的项目。有没有什么简单直接的方法可以做到这一点?我知道这些列表其实可以当作 set 来使用。

5 个回答

1
l1 = [4, 6, 3, 7]
l2 = [5, 5, 3, 1]
l3 = [2, 5, 4, 3]
l4 = [9, 8, 7, 6]

# first find the union of the "other" lists
l_union = reduce(set.union, (map(set, (l1, l2, l3))))

# then subtract the union from the remaining list
uniques = set(l4) - l_union

print uniques
>>> set([8, 9])

结果是:

4

使用集合类和其中定义的集合操作:

>>> l1 = [1,2,3,4,5,5]
>>> l2 = [3,4,4,6,7]
>>> set(l1) ^ set(l2)    # symmetric difference
set([1, 2, 5, 6, 7])

补充说明: 哦,我误解了你的问题。如果你的意思是“在 l1 中独特的元素,而这些元素不在 l2, l3, ..., ln 中”,那么:

l1set = set(l1)
for L in list_of_lists:   # list_of_lists = [l2, l3, ..., ln]
    l1set = l1set - set(L)
5
import collections

def uniques(*args):
    """For an arbitrary number of sequences,
           return the items in each sequence which
            do not occur in any of the other sequences
    """

    # ensure that each value only occurs once in each sequence
    args = [set(a) for a in args]

    seen = collections.defaultdict(int)
    for a in args:
        for i in a:
            seen[i] += 1
    # seen[i] = number of sequences in which value i occurs

    # for each sequence, return items
    #  which only occur in one sequence (ie this one)
    return [[i for i in a if seen[i]==1] for a in args]
uniques([1,1,2,3,5], [2,3,4,5], [3,3,3,9])  ->  [[1], [4], [9]]

所以

撰写回答