1

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?

user710028
  • 11
  • 2
  • 2
    How is "banana" a common element? – Jim Garrison Apr 15 '11 at 15:28
  • What have you written so far? Also, for your second question you should post exactly what you want as the result. – Jim Garrison Apr 15 '11 at 15:29
  • Sorry I mean Apple and Mango.I would like to know the occurrences of b[0][X] i.e. apple,ring,tennis etc in list a. For the second one I would like the list be to be printed out as :b=[[ 'apple','0','1','1','3'],[ 'apple','0','1','1','3'],[ 'mango','0','1','0','3']] – user710028 Apr 15 '11 at 16:12

1 Answers1

2

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
Simon Bergot
  • 10,378
  • 7
  • 39
  • 55
  • Noob question here: Would you mind explaining what zip(*a) does? – Amjith Apr 15 '11 at 19:07
  • 1
    it is a trick to perform a transposition on nested lists. see here for more details: http://stackoverflow.com/questions/19339/a-transpose-unzip-function-in-python – Simon Bergot Apr 16 '11 at 08:35