2016-07-18 38 views
-1

我需要將由列表生成的元素轉換爲整數,然後得到它們的總和。我想這樣做使用基本的循環將列表轉換爲整數,但不知道如何編寫代碼將列表轉換爲整數。到目前爲止,我的代碼出來的數據如下所示:將幾個單獨的列表轉換爲整數並得到總和

['9085', '5174'] 
['7297'] 
['9488'] 
['8370', '1014', '4870'] 
['4719'] 
['3004', '4969', '2458'] 
['9445', '7420'] 
['50', '1690', '8374'] 

...等等。我的代碼看起來像這樣到目前爲止:

import re 
hand = open('Regex-Actual.txt') 
numbers = [] 
for line in hand: 
    line = line.rstrip() 
    y= re.findall('[0-9]+',line) 
    if len(y) > 0 : 
     print y 
numbers = [int(y) for y in numbers] 
print numbers 

我是Python的初學者,所以解釋與答案意味着很多!

+0

數據Python數組/列表?或者它是否需要解析的字符串? –

+0

需要解析的幾個單獨的字符串。我猜先轉換爲整數,然後加在一起的總和。 – Egyrush

回答

2

你真的不需要使用正則表達式來解決這個問題,你可以很容易地從數字串中得到數字!

string_list = ['8370', '1014', '4870'] 
number_list = [int(x) for x in string_list] # using list comprehension 
sum(number_list) 
# 14254 

如果您從文件中讀取它,您可能會以列表的字符串形式獲取列表。例如,您將獲得"['8370', '1014', '4870']"。從此列出:

import ast 
lst = "['8370', '1014', '4870']" 
lst = ast.literal_eval(lst) 
#lst becomes ['8370', '1014', '4870'] 
+0

Hi @PeterWang。我擁有的列表非常廣泛,輸出是幾個單獨的字符串列表。我需要將這幾個單獨的列表轉換爲整數以將它們添加在一起。出於某種原因,列表理解不起作用,它可能是我輸入它的方式: import re hand = open('Regex-Actual.txt') for line in the hand: \t line = line .rstrip() \t Y = re.findall( '[0-9] +',線) \t如果len(Y)> 0: \t \t打印ŷ 數= [INT(X)爲X y中] 總和(數字) – Egyrush

相關問題