L1 = ['A', 'B', 'C', 'D']
L2 = [('A', 10)], ('B', 20)]
Now from these two list how can i generate common elements
output_list = [('A', 10), ('B', 20), ('C', ''), ('D', '')]
How can i get output_list using L1 and L2?
I tried the following
for i in L2:
for j in L1:
if i[0] == j:
ouput_list.append(i)
else:
output_list.append((j, ''))
But i'm not getting the exact out which i want
Lev Levitsky
66.4k23 gold badges155 silver badges184 bronze badges
asked Jun 4, 2012 at 6:43
Asif
1,8254 gold badges26 silver badges39 bronze badges
2 Answers 2
[(k, dict(L2).get(k, '')) for k in L1]
You can pull the dict(L2) out of the list comprehension if you don't want to recalculate it each time (e.g., if L2 is large).
d = dict(L2)
[(k, d.get(k, '')) for k in L1]
answered Jun 4, 2012 at 6:49
BrenBarn
253k39 gold badges421 silver badges392 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Asif
Thanks BrenBarn, This is what i actually want
In case you are sure the order of the lists is right and L2 is always shorter or same length:
from itertools import cycle
L2 + zip(L1[len(L2):], cycle(('',)))
answered Jun 4, 2012 at 6:58
Lev Levitsky
66.4k23 gold badges155 silver badges184 bronze badges
Comments
lang-py
common elements? Common in the sense of position, ASCII-number (i.e. ascending/descending sorting...)?