只从元组列表中获取整数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

所以,第一个似乎更有效率。 请注意,使用元组而不是列表更改等级,但对于onetwo较慢:

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()]
链接地址: http://www.djcxy.com/p/31705.html

上一篇: getting only integers from a list of tuples python 3

下一篇: How to Pythonically map content from one dict to another in a fail safe manner?