Nested List Comprehension
Posted on Mon 04 January 2010 in misc
I never really feel like i'm any good at using Python unless I am doing cool things with List Comprehension.
Here's a quick example of nested list comprehension I used today to create a new list from a list containing lists of three items
Visually:-
[['mostly cloudy (day)', 'cloudy3.png', 'cloudy3.png'],
['partly cloudy (night)', 'cloudy2_night.png', 'cloudy2_night.png'],
['partly cloudy (day)', 'cloudy2.png', 'cloudy2.png'],
....................................
['Sunny', 'sunny.png', 'sunny.png']]
To this:-
[['mostly cloudy (night)', 'cloudy3_night.png'],
['mostly cloudy (day)', 'cloudy3.png'],
['partly cloudy (night)', 'cloudy2_night.png'],
....................................
['Sunny', 'sunny.png']]
The code then:-
[[a[0],a[1]] for a in theList]