|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
simple list manipulation
i have a nested tuple/list such
a=[(1,2,3,4,5,6),(1,2,5,3,5,3),(2,4,5,3,4,3)] i want to create out of it another list with the elements of the second column for example : b=[2,2,4] . Do you have any idea ? i can just print such result but not as a new list Nikos |
|
#2
|
|||
|
|||
|
List comprehensions to the rescue!
Code:
>>> a=[(1,2,3,4,5,6),(1,2,5,3,5,3),(2,4,5,3,4,3)] >>> [x[1] for x in a] [2, 2, 4] There are other ways of doing it, but this is by far the simplest. In Python 2.4 you can also use a generator expression to create a generator that will retrieve the results when needed. For a large list this can be much more efficient: Code:
>>> gen = (x[1] for x in a) >>> gen.next() 2 >>> gen.next() 2 >>> gen.next() 4 >>> gen.next() Traceback (most recent call last): File "<stdin>", line 1, in ? StopIteration >>> Dave - The Developers' Coach Last edited by DevCoach : December 5th, 2004 at 07:13 PM. |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > simple list manipulation |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|