从其他列表变量中创建新列表

时间:2014-05-27 08:00:12

标签: python list math append

当我想从精心选择的整数变量中创建一个新列表,并询问新列表的总和时,我得到的答案总是为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:

而不是0,程序应该打印40

2 个答案:

答案 0 :(得分:2)

您可以使用“string.replace”将“ - ”转换为“”,然后将值转换为int

>>> esplit = ["34", "-3", "5", "--4"]
>>> sum([int(itm.replace("--", "")) for itm in esplit])
40

答案 1 :(得分:1)

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