在列表/集合中查找唯一元素的代码 [英] Code to find unique elements among lists / sets

查看:135
本文介绍了在列表/集合中查找唯一元素的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据如何将其翻译成python代码?该代码必须与上述表达式中提供的设置操作紧密相关,至少这是首选项.该代码必须足够通用,才能处理3个以上的列表.

How to translate this into python code? The code must closely correlate to the set operations as provided in the above expression, at least that is the preference. The code must be generic enough to handle more more than 3 lists as well.

更新: 似乎Wolfram正在抛出错误的维恩图? 另外,我们真正想要的是

UPDATE: Seems like Wolfram is throwing up an erroneous venn diagram? Also, what we actually want is

(A XOR B XOR C) - (A AND B AND C)

而我无法在Wolfram中表示.

and I am not able to represent that in Wolfram.

推荐答案

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}

这篇关于在列表/集合中查找唯一元素的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆