簡體   English   中英

將整數列表轉換為整數python

[英]Convert list of integers to an integer python

我有一個整數列表:

lists = [8,7,2]

我希望它是:

result = 872

我可以通過以下方式做到這一點:

result = 0
for count, i in enumerate(reversed(lists)):
    result += i*(10**count)

有用。 但我認為應該有另一種更好,更快的方法。 提前致謝

你也可以

from functools import reduce
reduce(lambda x,y: 10*x+y, (lists))

無需轉換為字符串並返回。

(出於完整性考慮)當列表可能包含大於9的數字時,您可以執行比轉換為字符串更快但更復雜的操作。

from functools import reduce
def combine(x,y):
    temp =y
    if (temp==0): 
        return x*10
    while(temp>0):
        x*=10
        temp//=10
    return x + y

reduce(combine,lists)

你可以試試這個

int("".join(list(map(str,lists))))

將所有整數映射到字符串,然后將它們連接起來並轉換回整數。

您也可以只對字符串進行外觀處理:

lists=[8, 7, 2]
result = int((str(lists)).strip("[]").replace(", ",""))

這是使用int,str和list理解的另一種簡單方法。

lists = [8,7,2]
result = int("".join([str(l) for l in lists]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM