getting only integers from a list of tuples python 3
I have a list of tuples like this:
[(a,3), (b, 4), (c, 5), (d, 1), (e,2)]
and I'd like to extract a list like this from it:
[3, 4, 5, 1, 2]
How would I go about this? I haven't been able to figure out how to do it.
Readability is secondary to speed in this context, as this code will be tucked away in a relatively well commented function.
If goal is efficiency, let's look at the different methods:
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))
Results:
one: 0.8771702060003008
two: 1.0403959849991224
three: 1.5230304799997612
four: 1.9551190909996876
five: 1.3489514130005773
So, the first one seems to be more efficient. Note that use tuple instead of list change the ranks, but is slower for one
and two
:
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)]
If every time numbers on second position:
numbers = [item[1] for item in tuples]
Elif number is integer:
numbers = [value for item in tuples for value in item if isinstance(value, int)]
Elif number is string like '3':
numbers = [value for item in tuples for value in item if isinstance(value, str) and value.isdigit()]
链接地址: http://www.djcxy.com/p/31706.html
上一篇: typeof是一个运算符和一个函数
下一篇: 只从元组列表中获取整数python 3