2017-01-19 51 views
1

一個如何去打開一個清單,裏面的元組,在形式,演員裏面列表元組爲int

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

與它整型,像一個列表,

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

以最有效的方式嗎?我已經嘗試過遞歸,但對於大型列表(數千個元組)來說,它太昂貴了。要解決這個問題

回答

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] 
+0

'enumerate'是一個更好的選擇...... – AChampion

+0

@AChampion感謝,我敢肯定有一個有效的解決方案numpy的存在以及.. – alecxe

1

將數字列表轉換爲數字相對簡單。將它們轉換爲字符串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類型。

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 
+0

這將是巨大的,如果你可以添加的執行時間[我的功能](http://stackoverflow.com/a/41734122/2063361)。爲什麼要忽略一個:P –

+1

@MoinuddinQuadri作爲pow2添加了你的建議,我決定先排除它,因爲其他建議中的其中一個有相同的原則,所以我沒有假設性能有很大的差異。 – niemmi

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]