x = [1,2,3,4,5,6,7]
y = [2,1,4,5,8,10]
z = [7,1,3,6,0]
如何找到这三个列表的维恩图中的所有元素(或者我甚至可以使用集合)
我正在处理大小为500-1000的DataFrame。我尝试使用Dataframes的条件子集。 在python中有一个更简单,更简单的方法吗? 我对集合,numpy数组甚至列表持开放态度。
答案 0 :(得分:4)
假设:
x = [1,2,3,4,5,6,7]
y = [2,1,4,5,8,10]
z = [7,1,3,6,0]
尝试:
x = set([1,2,3,4,5,6,7])
y = set([2,1,4,5,8,10])
z = set([7,1,3,6,0])
然后你可以通过以下方式找到交叉点:
xy = x.intersection(y)
xyz = x.intersection(y).intersection(z)
# and
xyz = x & y & z
另请参阅:https://docs.python.org/2/library/sets.html#set-objects
所有增量:
我已将'x_'用于'NOT in x'
x_y_z = z.difference(x).difference(y)
x_yz_ = y.difference(x).difference(z)
x_yz = y.intersection(z).difference(x)
xy_z_ = x.difference(y).difference(z)
xy_z = x.difference(y).intersection(z)
xyz_ = x.intersection(y).difference(z)
xyz = x.intersection(y).intersection(z)
答案 1 :(得分:0)
从@ PascalVKooten的回答中我编写了代码来查找任意三组之间的所有增量。
所有增量:
我使用了惯例' x _'对于'不在x'
x_y_z = z.difference(x).difference(y)
x_yz_ = y.difference(x).difference(z)
x_yz = y.intersection(z).difference(x)
xy_z_ = x.difference(y).difference(z)
xy_z = x.difference(y).intersection(z)
xyz_ = x.intersection(y).difference(z)
xyz = x.intersection(y).intersection(z)
使用以下方法测试代码: 每个结果集的交集应为空集。
x_y_z.intersection(x_yz_).
intersection(x_yz).\
intersection(xy_z).\
intersection(xy_z_).\
intersection(xy_z).\
intersection(xyz_).\
intersection(xyz)
结果集的联合应该等于三个集的并集。
x_y_z.union(x_yz _)。联盟(x_yz).union(xy_z _)。联盟(xy_z).union(XYZ _)。\ union(xyz)== x.union(y).union(z)'