且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在列表/集合中查找唯一元素的代码

更新时间:2023-02-17 18:06:50

Python支持集合(

Python supports sets (more about sets). For three lists it will be:

A = [1, 2, 3, 4]
B = [2, 3, 5, 6]
C = [3, 4, 5, 7]
As = set(A)
Bs = set(B)
Cs = set(C)

print((As ^ Bs ^ Cs) ^ (As & Bs & Cs))

对于列表列表(这是错误的-它所做的就是对所有集合进行异或"运算,然后对所有集合进行异或"运算,而对这两个结果进行异或"运算-下面是正确的解决方法):

import functools

def do_xor(s1, s2):
    return s1 ^ s2

def do_and(s1, s2):
    return s1 & s2

def do_task(list_of_lists):
    list_of_sets = list(map(set, list_of_lists))
    xors = functools.reduce(do_xor, list_of_sets)
    ands = functools.reduce(do_and, list_of_sets)
    return xors ^ ands

A = [1, 2, 3, 4]
B = [2, 3, 5, 6]
C = [3, 4, 5, 7]
D=[A, B, C]
print(do_task(D))

正确的解决方案:

import functools 

def do_or(s1, s2):
    return s1 | s2

def do_task2(list_of_lists):
    list_of_sets = list(map(set, list_of_lists))
    list_of_intersects = [X & Y for X in list_of_sets for Y in list_of_sets if X is not Y]
    intersects = functools.reduce(do_or, list_of_intersects)
    ors = functools.reduce(do_or, list_of_sets)
    return ors - intersects

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

print(do_task2(lol33)) # {1, 4}