简体   繁体   中英

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.

    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

You might use "string.replace" to turn "--" into "" and then convert values into 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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM