仅从元组列表中获取整数 python 3

getting only integers from a list of tuples python 3

我有一个这样的元组列表:

[(a,3), (b, 4), (c, 5), (d, 1), (e,2)]

我想从中提取这样的列表:

[3, 4, 5, 1, 2]

我该怎么做?我还没弄清楚该怎么做。

在此上下文中,可读性次于速度,因为此代码将隐藏在注释相对较好的函数中。

如果目标是效率,让我们看看不同的方法:

from timeit import timeit
from operator import itemgetter

T = [('a',3), ('b', 4), ('c', 5), ('d', 1), ('e',2)] 

def one():
    [v for _, v in T]

def two():
    [v[-1] for v in T]

def three():
    list(map(itemgetter(1), T))

def four():
    list(map(lambda x:x[1], T))

def five():
    list(zip(*T))[1]

for func in (one, two, three, four, five):
    print(func.__name__ + ':', timeit(func))

结果:

one: 0.8771702060003008
two: 1.0403959849991224
three: 1.5230304799997612
four: 1.9551190909996876
five: 1.3489514130005773

所以,第一个似乎更有效率。 请注意,使用元组而不是列表更改排名,但速度较慢 :

one: 1.620873247000418  # slower
two: 1.7368736420003188  # slower
three: 1.4523903099998279
four: 1.9480371049994574
five: 1.2643559589996585

获胜发电机:

from operator import itemgetter
l = [(a,3), (b, 4), (c, 5), (d, 1), (e,2)]
r = map(itemgetter(1), l)
tuples = [(a,3), (b, 4), (c, 5), (d, 1), (e,2)]

如果每次第二位的数字:

numbers = [item[1] for item in tuples]

Elif 数为整数:

numbers = [value for item in tuples for value in item if isinstance(value, int)]

Elif 数字是类似于“3”的字符串:

numbers = [value for item in tuples for value in item if isinstance(value, str) and value.isdigit()]

这是使用 zip 的另一种方法:

>>> l = [('a',3), ('b', 4), ('c', 5), ('d', 1), ('e',2)]
>>> list(zip(*l))[1]
(3, 4, 5, 1, 2)

如果你真的需要 list 而不是 tuple:

>>> list(list(zip(*l))[1])
[3, 4, 5, 1, 2]

你可以这样做:

>>> map(lambda x:x[1], lst)
[3, 4, 5, 1, 2]

在python3中,做:

>>> list(map(lambda x:x[1], lst))