How to cut list of tuples in python?

Assuming that:

L = [(0,'a'), (1,'b'), (2,'c')]

How to get 0each index tupleas a mock result:

[0, 1, 2]

To get this, I used python list comprehensionand solved the problem:

[num[0] for num in L]

However, it should be a pythonic way of slicing it like L[:1] that, but of course this smoothing doesn't work.

Is there a better solution?

+4
source share
4 answers

You can use *unpacking with zip().

>>> l = [(0,'a'), (1,'b'), (2,'c')]
>>> for item in zip(*l)[0]:
...     print item,
...
0 1 2

Python 3 zip() list, zip list(), next(iter()) -:

>>> l = [(0,'a'), (1,'b'), (2,'c')]
>>> print(*next(iter(zip(*l))))
0 1 2

.

+5

;

tuples = [(0,'a'), (1,'b'), (2,'c')]
print zip(*tuples)[0]

... "", .

+2
>>> list = [(0,'a'), (1,'b'), (2,'c')]
>>> l = []
>>> for t in list:
        l.append(t[0])
0
source

How about map?

map(lambda (number, letter): number, L)

To cut it into python 2

map(lambda (number, letter): number, L)[x:y]

In python 3, you must first convert it to a list:

list(map(lambda (number, letter): number, L))[x:y]
0
source

Source: https://habr.com/ru/post/1616754/


All Articles