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

时间:2017-03-15 08:31:07

标签: python list

例如:

如果我有三个列表,如

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

这三个列表是我的输入,

我的预期输出就像

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

3 个答案:

答案 0 :(得分:2)

列表解析通过转换为集合来删除列表中的重复项,并通过明确检查每个元素在列表之间重复:

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                                
"""                   

这是丑陋的,长期的,低效的,我强烈建议反对它,但它可能

如果您使用lists = [[3, 1, 1], [2, 4, 3], [3, 4, 5]],则会获得正确的输出

[[3, 1], [2, 4], [5]]

也保留原始订单。

答案 1 :(得分:1)

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

使用函数和列表推导:

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


def is_new_element(element, my_set):
    if element in my_set:
        return False
    else:
        my_set.add(element)
        return True

already_seen = set()
print([[x for x in l if is_new_element(x, already_seen)] for l in my_lists])
# [[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]]

答案 2 :(得分:0)

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]