简体   繁体   English

汇总列表元素

[英]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 ',' . 造成错误的原因是,当您应为sum提供一个整数值( iatt = int(i) )时,应为其提供以','分隔的列表的内容。

You have a couple of options for this. 您有两个选择。 Either provide a comprehension to sum and cast every element to an int inside the comprehension: 要么提供一种理解,以将所有元素sum并转换为该理解内的int

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

or, use a built-in like map which pretty much does the same thing: 或者,使用内置的类似map几乎相同:

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

in both cases, sum expects something that can be iterated through and it handles the summing. 在这两种情况下, sum希望可以迭代某些内容,并处理求和。

Of course, you could manually loop over the contents of att , adding int(i) to total as you go: 当然,您可以手动遍历att的内容,并在运行时将int(i)添加到total中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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