简体   繁体   中英

Summing List Elements

I'm trying to do this question for this online coding course I'm part of, and one of the questions requires me to add together integers in a list. I've tried to find the answer (and visited a few other pages on this site), but I can't think of anything. Help please!

Here's my code so far:

total = 0
att = input("RSVPs: ")
att = att.split(",")
for i in att:
  print(sum(iatt) for i in att)

在此处输入图片说明

Your error is caused because you provide sum with an integer value ( iatt = int(i) ) when you should be providing it with the contents of the list which is split on ',' .

You have a couple of options for this. Either provide a comprehension to sum and cast every element to an int inside the comprehension:

print(sum(int(i) for i in att))

or, use a built-in like map which pretty much does the same thing:

print(sum(map(int,att)))

in both cases, sum expects something that can be iterated through and it handles the summing.

Of course, you could manually loop over the contents of att , adding int(i) to total as you go:

for i in att:
    total += int(i)
print(total)    

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