2011-03-09 51 views
1

所有,將int轉換爲單個數字的列表更快?

我想限定INT(987654321)< => [9,8,7,6,5,4,3,2,1]轉換器,如果INT數<長度9,例如列表將爲[0,0,0,0,0,0,0,1,0] ,並且如果該長度> 9,例如9987654321,列表會[9,9,8,7,6,5,4,3,2,1]

>>> i 
987654321 
>>> l 
[9, 8, 7, 6, 5, 4, 3, 2, 1] 
>>> z = [0]*(len(unit) - len(str(l))) 
>>> z.extend(l) 
>>> l = z 
>>> unit 
[100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1] 

>>> sum([x*y for x,y in zip(l, unit)]) 
987654321 
>>> int("".join([str(x) for x in l])) 
987654321 


>>> l1 = [int(x) for x in str(i)] 
>>> z = [0]*(len(unit) - len(str(l1))) 
>>> z.extend(l1) 
>>> l1 = z 
>>> l1 
[9, 8, 7, 6, 5, 4, 3, 2, 1] 

>>> a = [i//x for x in unit] 
>>> b = [a[x] - a[x-1]*10 for x in range(9)] 
>>> if len(b) = len(a): b[0] = a[0] # fix the a[-1] issue 
>>> b 
[9, 8, 7, 6, 5, 4, 3, 2, 1] 

我上面測試s解決方案,但發現這些可能不會比我想要的更快/更簡單,並且可能在內部存在長度相關的錯誤,任何人都可以與我分享更好的解決方案來進行此類轉換嗎?

謝謝!

+1

你測試過速度了嗎?你的時間是什麼? – 2011-03-09 07:52:11

+0

我稍後會粘貼測試結果,但我認爲字符串約定應該比int數操作要慢。 – user478514 2011-03-09 08:29:09

回答

10

也許我錯過了一些東西,但是這不夠(沒有檢查值)?

def int_to_list(i): 
    return [int(x) for x in str(i).zfill(9)] 

def list_to_int(l): 
    return int("".join(str(x) for x in l)) 

參考:str.zfill

+0

感謝zfill() – user478514 2011-03-09 08:26:47

0
def convert(number): 
    stringified_number = '%s' % number 
    if len(stringified_number) < 9: 
     stringified_number = stringified_number.zfill(9) 
    return [int(c) for c in stringified_number] 

>>> convert(10) 
[0, 0, 0, 0, 0, 0, 0, 1, 0] 

>>> convert(987654321) 
[9, 8, 7, 6, 5, 4, 3, 2, 1] 
1

又是怎麼回事:

def int_to_list(num) 
    return list ("%010d" % num) 
0

要通過整數位放置任何長度的整成一個列表順序 -

a = 123456789123456789123456789123456789123456789123456789 
j = len('{}'.format(a)) 
b = [0 for i in range(j)] 
c = 0 
while j > 0: 
    b [c] = a % 10**j // 10**(j-1) 
    j = j-1 
    c = c + 1 
print(b) 

輸出 -

[1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2,3 ,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1 ,2,3,4,5,6,7,8,9]

您可以將條件放在j替代b的分配。