将列表中的元组转换为int

时间:2017-01-19 04:52:46

标签: python list int tuples

如何以其中的元组形式转换列表,

list = [(1, 9, 7), (1, 5, 6), (1, 7), (1, 4), (7, 4), (7,)]

进入一个包含ints的列表,比如

list = [197, 156, 17, 14, 74, 7]

以最有效的方式?我尝试过递归,但对于大型列表(数千个元组)而言,它的内存太贵了。

4 个答案:

答案 0 :(得分:4)

您可以使用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

答案 1 :(得分:2)

解决问题的一种方法是将子列表中的每个整数转换为字符串,加入并转换为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]

答案 2 :(得分:1)

将数字列表转换为数字相对简单。将它们转换为字符串> docker run -itd ubuntu 03c55e9ba9de3e0b80ad9f3e0629dc63f4ab65291b79e133af2b392030ffc17d > docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 03c55e9ba9de ubuntu "/bin/bash" 2 minutes ago Up 2 minutes gallant_hypatia 并转换回for file in dirs: if file != '.git': print(file) new_file_path = osp.join(repo1.working_tree_dir, file) print(new_file_path) print(repo1.index) #open(file,'w').close repo1.index.add([new_file_path]) 。或者你可以用数学方式做到这一点:

join()

注意:不要将int用作变量名,因为这会隐藏python >>> [sum(n*10**e for e, n in enumerate(reversed(item))) for item in l] [197, 156, 17, 14, 74, 7] 类型。

答案 3 :(得分:0)

您也可以使用一点点数学来实现这一目标。在这里,我将元组中的数字与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]