我有两个清单:
a= [['tea','apple',1,1],['coffee','apple',0,1],['cola','mango',1,1],['lemon','banana',0,0]]
b=[[ 'apple','0','1','1','3'],[ 'ring','0','1','1','3'],[ 'tennis','1','0','0','3'],[ 'mango','0','1','0','3']]
我正在努力找出最好的方法:
[ 'apple','0','1','1','3']
列出b。如果列表中有2个苹果条目,那么我想在b中添加两个['apple',...]
块。列表应该类似于:b = [['apple','0','1',' 1','3'],['apple','0','1','1','3'],['mango','0','1','0','3' ] 有没有更简单的方法呢?
答案 0 :(得分:2)
为1,最好是使用set():
a= [['tea','apple',1,1],
['coffee','apple',0,1],
['cola','mango',1,1],
['lemon','banana',0,0]]
b=[[ 'apple','0','1','1','3'],
[ 'ring','0','1','1','3'],
[ 'tennis','1','0','0','3'],
[ 'mango','0','1','0','3']]
a_columns = zip(*a)
# union
a_set = set(a_columns[0]) | set(a_columns[1])
b_columns = zip(*b)
b_set = set(b_columns[0])
# intersection
common_names = a_set & b_set
print common_names