簡體   English   中英

從其他列表變量中創建新列表

[英]Making new lists out of other list variables

當我想從精心選擇的整數變量中創建一個新列表,並要求新列表的總和時,我得到的答案始終為0。

    else:
        if "--" in epart:
            epart = epart[2:]
            esplit = [int(epart) for epart in esplit]
            total.append(epart)
        else:
            epart = [int(epart) for epart in esplit]
            total.append(epart)

print sum(total)

代碼的頂部是:

total = []

如果出現以下情況,如何獲取代碼以打印總計的代碼

esplit = ["34", "-3", "5", "--4"]
for epart in esplit:

程序應打印40,而不是0

您可以使用“ string.replace”將“-”轉換為“”,然后將值轉換為int

>>> esplit = ["34", "-3", "5", "--4"]
>>> sum([int(itm.replace("--", "")) for itm in esplit])
40
esplit = ["34", "-3", "5", "--4"]
print sum([int(elem[2:]) if "--" in elem else int(elem) for elem in esplit])

暫無
暫無

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

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