开发者

Python how to search accross the lists

开发者 https://www.devze.com 2023-02-25 07:34 出处:网络
I have two lists: a= [[\'tea\',\'apple\',1,1],[\'coffee\',\'apple\',0,1],[\'cola\',\'mango\',1,1],[\'lemon\',\'banana\',0,0]]

I have two lists:

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']]

I am trying to figure out the best possible way to :

  1. List item
  2. Locate/search the the common elements between : a and b in list a ( i.e. apple and mango in list a).
  3. For number of entries of e.g. apple in list a, I would like to add entire [ 'apple','0','1','1','3'] to list b. If there are 2 apple entries in list a then I would like to add two ['apple',...] blocks in b.The list be should look something like :b=[[ 'apple','0','1','开发者_开发知识库1','3'],[ 'apple','0','1','1','3'],[ 'mango','0','1','0','3']]

Is there any easier way to do this?


for 1, the best is to use 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
0

精彩评论

暂无评论...
验证码 换一张
取 消