[Tutor] Is this a job for zip(), or some other way?
Alfred Milgrom
fredm at smartypantsco.com
Thu Mar 25 19:11:32 EST 2004
At 06:58 PM 25/03/04 -0500, R. Alan Monroe wrote:
>Given:
>[ ('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576), ....
>arbitrary n number of tuples in this list]
>
>I want to return:
>[ ['bob', 'mike', 'steve',... up to n elements],
> [24, 20, 30, .... n],
> [457, 4567, 576, .... n] ]
>
>I played around with zip and list comprehensions but I was too burnt
>out to get it, today. Any ideas?
>Alan
If you can be sure you always have the same format in the tuples, then list
comprehension can do it, relatively easily:
original = [ ('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576),]
result = [[a[0] for a in original], [a[1] for a in original], [a[2] for a
in original]]
print result
[['bob', 'mike', 'steve'], [24, 20, 30], [457, 4567, 576]]
(I don't know enough about zip to do it another way :)
Hope this helps,
Fred Milgrom
More information about the Tutor
mailing list