一个如何去打开一个清单,里面的元组,在形式,演员里面列表元组为int
list = [(1, 9, 7), (1, 5, 6), (1, 7), (1, 4), (7, 4), (7,)]
与它整型,像一个列表,
list = [197, 156, 17, 14, 74, 7]
以最有效的方式吗?我已经尝试过递归,但对于大型列表(数千个元组)来说,它太昂贵了。要解决这个问题
一个如何去打开一个清单,里面的元组,在形式,演员里面列表元组为int
list = [(1, 9, 7), (1, 5, 6), (1, 7), (1, 4), (7, 4), (7,)]
与它整型,像一个列表,
list = [197, 156, 17, 14, 74, 7]
以最有效的方式吗?我已经尝试过递归,但对于大型列表(数千个元组)来说,它太昂贵了。要解决这个问题
一种方法是强制转换为字符串,每个整数的子列表,加入并转换为int
:
In [1]: l = [(1, 9, 7), (1, 5, 6), (1, 7), (1, 4), (7, 4), (7,)]
In [2]: [int("".join(map(str, item))) for item in l]
Out[2]: [197, 156, 17, 14, 74, 7]
或者,使用几十功率(由已公布答案的变化@AChampion):
In [3]: [sum(10 ** index * value for index, value in enumerate(reversed(item)))
for item in l]
Out[3]: [197, 156, 17, 14, 74, 7]
将数字列表转换为数字相对简单。将它们转换为字符串join()
并转换回int
。或者你也可以更数学上做到这一点:
>>> [sum(n*10**e for e, n in enumerate(reversed(item))) for item in l]
[197, 156, 17, 14, 74, 7]
注:请不要使用list
作为变量名,因为这会隐藏蟒蛇list
类型。
你可以使用functools.reduce
每一个元组转换:
>>> from functools import reduce
>>> l = [(1, 9, 7), (1, 5, 6), (1, 7), (1, 4), (7, 4), (7,)]
>>> [reduce(lambda x,y: x*10+y, t) for t in l]
[197, 156, 17, 14, 74, 7]
更新由于问题问的有效方法,这里有参考答案测量:
import itertools as it
import functools
def conv_reduce(l):
return [functools.reduce(lambda x,y: x*10+y, t) for t in l]
def conv_str(l):
return [int("".join(map(str, item))) for item in l]
def conv_pow(l):
return [sum(n*10**e for n, e in zip(reversed(item), it.count())) for item in l]
def conv_pow2(l):
return [sum(t[-i-1]*(10**i) for i in range(len(t))) for t in l]
if __name__ == '__main__':
import timeit
print('reduce', timeit.timeit("conv_reduce(l)", setup="from __main__ import conv_reduce; l = [(1, 9, 7), (1, 5, 6), (1, 7), (1, 4), (7, 4), (7,)]"))
print('str', timeit.timeit("conv_str(l)", setup="from __main__ import conv_str; l = [(1, 9, 7), (1, 5, 6), (1, 7), (1, 4), (7, 4), (7,)]"))
print('pow', timeit.timeit("conv_pow(l)", setup="from __main__ import conv_pow; l = [(1, 9, 7), (1, 5, 6), (1, 7), (1, 4), (7, 4), (7,)]"))
print('pow2', timeit.timeit("conv_pow2(l)", setup="from __main__ import conv_pow2; l = [(1, 9, 7), (1, 5, 6), (1, 7), (1, 4), (7, 4), (7,)]"))
输出:
reduce 2.5965667460041004
str 5.068828338997264
pow 7.192991987001733
pow2 8.017168823003885
这将是巨大的,如果你可以添加的执行时间[我的功能](http://stackoverflow.com/a/41734122/2063361)。为什么要忽略一个:P –
@MoinuddinQuadri作为pow2添加了你的建议,我决定先排除它,因为其他建议中的其中一个有相同的原则,所以我没有假设性能有很大的差异。 – niemmi
你也可以用一点数学来实现这一点。在这里,我以相反的顺序将元组中的数字乘以10
的功率以获得数字。
>>> my_list = list = [(1, 9, 7), (1, 5, 6), (1, 7), (1, 4), (7, 4), (7,)]
# v sum numbers based on their position at hundred, tens, ones place
>>> [sum(t[-i-1]*(10**i) for i in range(len(t))) for t in my_list]
[197, 156, 17, 14, 74, 7]
'enumerate'是一个更好的选择...... – AChampion
@AChampion感谢,我敢肯定有一个有效的解决方案numpy的存在以及.. – alecxe