使用python删除列表内和列表外的重复值

使用python删除列表内和列表外的重复值,python,list,Python,List,例如: 如果我有三份清单,比如 l1 = [1,2] l2 = [2,3] l3 = [1,4] 这三个列表是我的输入 我的预期输出是 l1 = [1,2] l2 = [3] l3 = [4] 一种列表理解,通过转换为集合来删除列表中的重复项,通过显式检查每个元素来删除列表之间的重复项: l1 = list(set(l1)) l2 = [x for x in set(l2) if not x in l1] l3 = [x for x in set(l3) if not x in l1 and

例如:

如果我有三份清单,比如

l1 = [1,2]
l2 = [2,3]
l3 = [1,4]
这三个列表是我的输入

我的预期输出是

l1 = [1,2]
l2 = [3]
l3 = [4]

一种列表理解,通过转换为集合来删除列表中的重复项,通过显式检查每个元素来删除列表之间的重复项:

l1 = list(set(l1))
l2 = [x for x in set(l2) if not x in l1]
l3 = [x for x in set(l3) if not x in l1 and not x in l2]
编辑:既然你要求一行(为什么?!),这里有一行-在评论中有一些解释:

print [[element for n, element in enumerate(sublist) if n == sublist.index(element) and not element in list(chain(*lists[:sublistIndex]))] for sublistIndex, sublist in enumerate(lists)]
"""
        \-------------------------------------------------------------------------/     \-------------------------------------------------/
          use this element if it's that value's first occurrence in the sublist...      and it doesn't occur in the joined earlier sublists                                
"""                   
它丑陋、冗长、效率低下,我强烈建议不要这样做,但这是可能的

如果将它与
列表=[[3,1,1],[2,4,3],[3,4,5]]
一起使用,您将获得正确的输出

[[3, 1], [2, 4], [5]]
也要保持原来的秩序

l1 = [1,2]
l2 = [2,3]
l3 = [1,4]
l1s = set(l1)
l2s = set(l2)
l3s = set(l3)

print(list(l1),list(l2s-l1s),list(l3s-(l1s.union(l2s))))
输出

[1, 2] [3] [4]

您可以保留一个保存所有元素的集合。如果元素不在集合中,请将其添加到集合和当前列表中。这两个备选方案适用于任意数量的元素和列表,并保持原始顺序:

使用函数和列表理解: 具有双回路: 它有点冗长,但不需要任何新功能:

my_lists = [
        [1,2],
        [2,3],
        [1,4]
    ]   

uniq_lists = []
already_seen = set()

for lst in my_lists:
    uniq_list = []
    for element in lst:
        if element not in already_seen:
            already_seen.add(element)
            uniq_list.append(element)
    uniq_lists.append(uniq_list)

print(uniq_lists)
# [[1, 2], [3], [4]]

是否可以在单行代码中执行此操作?预期的输出也可能类似于列表中的列表示例:[[1,2],[3],[4]]这当然不会保留原始列表顺序,不确定这是否重要
my_lists = [
        [1,2],
        [2,3],
        [1,4]
    ]   

uniq_lists = []
already_seen = set()

for lst in my_lists:
    uniq_list = []
    for element in lst:
        if element not in already_seen:
            already_seen.add(element)
            uniq_list.append(element)
    uniq_lists.append(uniq_list)

print(uniq_lists)
# [[1, 2], [3], [4]]