2016-05-03 94 views
-1

我试图计算给定列表中的数字并只计算偶数。我不断收到语法错误,不知道问题是什么。计算给定列表中的偶数

x = [1,5,4,7,2,10,8,19,27,26,54,80] 

def count_evens(g_list): 
    y = 0 
    for i in g_list: 
     if g_list[i] % 2 = 0: 
      y = y + 1 
     else: 
      y = y + 0 
    print(str(y)) 

count_evens(x) 

语法错误来自if g_list[i] % 2 = 0:我的语法有什么问题?

谢谢!

+0

应该== –

+0

它应该是 “==” – sashas

+0

[这](http://scipython.com/book/chapter-4-the-core- python-language-ii/examples/assignment-vs-the-comparison-operator /)对Assignment vs Comparison有很好的解释。 – NonlinearFruit

回答

1

语法错误

要比较,以便使用===(单等于是分配)

if g_list[i] % 2 == 0: 

指数超出范围

遍历li的所有元素ST,你可以用这种形式:

for i in g_list: 
    if i % 2 == 0: # No need for g_list[i] 
        # in your for loop, 
        # i is an element from the list, not an index 
+0

哦。我的。神。我是一个白痴:/ 这就是睡眠不足对你来说,大声笑 但现在它说的索引超出范围。我是否需要为范围做一个FOR循环,然后为列表中的每个[i]做另一个循环? – Muldawg2020

+0

@ Muldawg2020当你在列表中使用'for i'时,你不需要使用'list [i]',只是'i' – bakkal

+0

Jeez,现在工作正常。仍然习惯了这个:/ 非常感谢帮助。非常感谢。一旦它让我,我会关闭它:) – Muldawg2020

0

g_list[i] % 2 = 0是一个赋值语句(以及因为“不能分配给操作符”而导致的非法赋值语句)。在if语句(仅表达式)中不允许赋值语句。

你想g_list[i] % 2 == 0这是一个逻辑表达式。