[Tutor] Iterating through two lists at the same time with manipulation..
Kent Johnson
kent37 at tds.net
Fri Jun 29 04:37:48 CEST 2007
Iyer wrote:
> 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 ?
If you want the result ordered by the first element, you can combine
the two lists, sort the combined list, and use itertools.groupby() to
collect the groups:
In [1]: list1 = [[1,'A'],[2,'B'],[3,'C'],[4,'D']]
In [2]: list2 = [[1,'AA'],[3,'CC'], [4,'DD']]
In [3]: import itertools, operator
In [4]: l=list1+list2
In [5]: l.sort()
In [7]: [ list(g) for k, g in itertools.groupby(l,
key=operator.itemgetter(0))]
Out[7]:
[[[1, 'A'], [1, 'AA']],
[[2, 'B']],
[[3, 'C'], [3, 'CC']],
[[4, 'D'], [4, 'DD']]]
If you don't care about order, you can use a dict to collect like items:
In [8]: d={}
In [9]: for i in l:
...: d.setdefault(i[0], []).append(i)
In [11]: d.values()
Out[11]:
[[[1, 'A'], [1, 'AA']],
[[2, 'B']],
[[3, 'C'], [3, 'CC']],
[[4, 'D'], [4, 'DD']]]
These are in order but in general they will not be.
If you want to preserve the original order then I think you will have to
do it "by hand" as John suggests.
Kent
More information about the Tutor
mailing list