我想找到多维列表与第一个元素之间的交集,但我无法找到解决方案。
示例:
a = [[greg ,1.2 ,400 ,234] [top ,9.0 ,5.1 ,2300] [file ,5.7 ,2.2, 900] [stop, 1.6 ,6.7 ,200]
b = [[hall,5.2 ,460 ,234] [line ,5.3 ,5.91 ,100] [file ,2.7 ,3.3, 6.4] [stop, 6.6 ,5.7 ,230]
我需要什么:
1.元素不在但在b中,我想仅与element[0]
期望输出= [[hall,5.2 ,460 ,234] [line ,5.3 ,5.91 ,100]]
2.元素不在b但在a中,我想仅与element[0]
期望输出= [greg ,1.2 ,400 ,234]
然后将缺失列表附加到a,反之亦然。
我有示例代码,但没有工作。
at = map(tuple,a)
bt = map(tuple,b)
st1 = set(at)
st2 = set(bt)
s1 = st1.intersection(st2)
s2 = st2.intersection(st1)
答案 0 :(得分:1)
您可以使用两个dicts并找到键的设置差异,其中键是每个第一个元素:
a = [["greg", 1.2, 400, 234], ["top", 9.0, 5.1, 2300], ["file", 5.7, 2.2, 900], ["stop", 1.6, 6.7, 200]]
b = [["hall", 5.2, 460, 234], ["line", 5.3, 5.91, 100], ["file", 2.7, 3.3, 6.4], ["stop", 6.6, 5.7, 230]]
d1 = {sub[0]: sub for sub in a}
d2 = {sub[0]: sub for sub in b}
print([d2[k] for k in d2.keys() - d1])
print([d1[k] for k in d1.keys() - d2])
输出:
[['hall', 5.2, 460, 234], ['line', 5.3, 5.91, 100]]
[['top', 9.0, 5.1, 2300], ['greg', 1.2, 400, 234]]
根据您问题中的预期输出,正确的输出为[['top', 9.0, 5.1, 2300], ['greg', 1.2, 400, 234]]
而不只是[['greg', 1.2, 400, 234]]
。
等效的python 2代码将需要使用 viewkeys :
print([d2[k] for k in d2.viewkeys() - d1])
print([d1[k] for k in d1.viewkeys() - d2])
答案 1 :(得分:0)
a = [["greg" ,1.2 ,400 ,234], ["top" ,9.0 ,5.1 ,2300], ["file" ,5.7 ,2.2, 900], ["stop", 1.6 ,6.7 ,200]]
b = [["hall",5.2 ,460 ,234], ["line" ,5.3 ,5.91 ,100], ["file" ,2.7 ,3.3, 6.4], ["stop", 6.6 ,5.7 ,230]]
b_prime = list()
i=0
for key in a:
if key[0] == b[i][0]:
i = i + 1
continue
print "entry ",key, " is not in a"
b_prime.append(key)
i = i + 1
a_prime = list()
i=0
for key in b:
if key[0] == a[i][0]:
i = i + 1
continue
print "entry ",key, " is not in b"
a_prime.append(key)
i = i + 1
print " "
print a
print b
print "need to add these to b", b_prime
print "need to add these to a", a_prime
i=0
for key in a_prime:
a.append(b[i])
i = i + 1
i=0
for key in b_prime:
b.append(a[i])
i = i + 1
print " "
print a
print b