[Tutor] Iterating through two lists at the same time with manipulation..
Iyer
maseriyer at yahoo.com
Fri Jun 29 03:05:51 CEST 2007
I have 2 lists:
List 1 has lists in it, such as
list1 = [[1,'A'],[2,'B'],[3,'C'],[4,'D']]
There is another list2 such as
list2 = [[1,'AA'],[3,'CC'], [4,'DD']]
For eg,
I wish to iterate over both the lists and produce the output
a = [[1,'A'],[1,'AA']]
b = [[2,'B']]
c = [[3,'C'],[3,'CC']]
d = [[4,'D'],[4,'DD']]
Or [a,b,c,d] where a,b,c,d are defined above
What would be the best and quickest way to carry this out ? This list comprehension doesn't seem to get the desired result:
[[x,y] for x in list1 for y in list2 if x[0]==y[0]]
the sub-list [2,'B'] in list1 is left out. i.e, the output is
[[[1, 'A'], [1, 'AA']], [[3, 'C'], [3, 'CC']], [[4, 'D'], [4, 'DD']]]
---------------------------------
Moody friends. Drama queens. Your life? Nope! - their life, your story.
Play Sims Stories at Yahoo! Games.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070628/ae4769ca/attachment.html
More information about the Tutor
mailing list