简体   繁体   English

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

[英]Making new lists out of other list variables

When i want to make a new list out of carefully selected integer variables, and ask for the sum of the new list, the answer i get is always 0. 当我想从精心选择的整数变量中创建一个新列表,并要求新列表的总和时,我得到的答案始终为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)

At the top of the code is: 代码的顶部是:

total = []

How do I get the code to print the sum of the totals , if: 如果出现以下情况,如何获取代码以打印总计的代码

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

Rather then 0, the program shoud print 40 程序应打印40,而不是0

You might use "string.replace" to turn "--" into "" and then convert values into int : 您可以使用“ 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