[Tutor] how to compare elements of 2 lists
Chris Fuller
cfuller at thinkingplanet.net
Wed Dec 26 19:11:51 CET 2007
On Wednesday 26 December 2007 10:03, Alan Gauld wrote:
> I thought I was following this but now I'm not sure.
>
> Do you mean that if I have a list L that contains an arbitrary
>
> number of sublists that I can call zip using:
> >>> zip(*L)
>
> rather than
>
> >>> zip(L[0],L[1],...., L[n])
>
> If so I agree.
>
Yes. You could build up a string and call eval(), but otherwise this wouldn't
be possible, without iterating through manually. (using evail() is usually
not a good idea, avoid it if you can)
> But any time that you use the *[] format it is easier to
> just put the content of the [] into the zip directly, which is what,
> I think, Kent is saying?
>
Yes, for the original example, zip(a,b) is equivalent, and probably clearer.
Certainly simpler. Sorry to be confusing. I realize now that lots of my
code have lists of known length and need a little tweaking :)
I just remembered another way to do this, with map():
>>> a=range(4)
>>> b=['a','b','c','d']
>>> map(None,a,b)
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
This also doesn't complain if the lists are uneven, but instead of truncating,
it pads the short ones with None's. I almost never use map() now that we
have list comprehensions, however. map(None, *(a,b)) also works if you
are "transposing" an unknown number of lists.
Cheers
More information about the Tutor
mailing list