简体   繁体   English

如何从python中的列表求和?

[英]How to sum numbers from list(s) in python?

Learning python for two days :) and now I attempting to solve Project Euler problem #2 and I need help. 学习了两天的Python :),现在我试图解决Euler项目问题​​2 ,我需要帮助。

To be more specific, I need know know how to add numbers that were added to a empty list. 更具体地说,我需要知道如何添加添加到空列表中的数字。 I tried 'sum' but doesn't seems to work how the tutorial sites suggest. 我尝试了“求和”,但似乎对教程网站的建议不起作用。 I'm using python 3. Here's my code so far: 我正在使用python3。到目前为止,这是我的代码:

a = 0
b = 1
n = a+b
while (n < 20):
   a, b = b, a + b
   n = a+b
   if n%2 == 0:
       mylist = []
       mylist.append(n)
       print(sum(mylist))

this outputs: 这个输出:

2
8

Now how do I add them? 现在如何添加它们? Thanks :) 谢谢 :)

You are doing it right (the summing of the list), the main problem is with this statement: 您做对了(列表的总和),主要问题在于以下语句:

mylist = []

move it before the while loop. while循环之前将其移动。 Otherwise you are creating an new empy mylist each time through the loop. 否则,您将在循环中每次创建一个新的empy mylist

Also, you probably want to print the sum of the list probably after you are done with your loop. 另外,您可能希望在完成循环打印列表的总和。

Ie, 也就是说,

...
mylist = []
while (n < 20):
   a, b = b, a + b
   n = a+b
   if n%2 == 0:
       mylist.append(n)

print(sum(mylist))

You are creating a new empty list just before you append a number to it, so you'll only ever have a one-element list. 您将在向其添加数字之前创建一个新的空列表,因此,您将只有一个元素列表。 Create the empty mylist once before you start. 开始之前,请先创建一个空的mylist。

Since it seems that you have the list issue resolved, I would suggest an alternative to using a list. 由于似乎您已经解决了列表问题,所以我建议您使用一种替代列表的方法。

Try the following solution that uses integer objects instead of lists: 尝试使用整数对象而不是列表的以下解决方案:

f = 0
n = 1
r = 0

s = 0

while (n < 4000000):
    r = f + n
    f = n
    n = r
    if n % 2 == 0:
        s += n

print(s)

Just as @Ned & @Levon pointed out. 就像@Ned和@Levon指出的那样。

a = 0
b = 1
n = a+b
mylist = []
while (n < 20):
   a, b = b, a + b
   n = a+b
   if n%2 == 0:
       mylist.append(n)
print(sum(mylist))

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

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