Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:列表理解无效语法错误_Python_List - Fatal编程技术网

Python:列表理解无效语法错误

Python:列表理解无效语法错误,python,list,Python,List,我试图在一行中重新创建此循环: results = [149, 0, 128, 0, 0, 0, 1, 0, 0, 14, 0, 2] for x in results: total = x + total print(total) 但当我这么做的时候: y = [total = total + x for x in results] 我得到一个错误: y = [total = total + x for x in results]

我试图在一行中重新创建此循环:

results = [149, 0, 128, 0, 0, 0, 1, 0, 0, 14, 0, 2] 

for x in results:
  total = x + total

print(total)
但当我这么做的时候:

 y = [total = total + x for x in results]
我得到一个错误:

y = [total = total + x for x in results]                                                                                                                                       
                   ^                                                                                                                                                                   
SyntaxError: invalid syntax  

我错过了什么?谢谢。

您只需要使用一个函数:

results = [149, 0, 128, 0, 0, 0, 1, 0, 0, 14, 0, 2]
res = sum(results)
print(res)


如果你坚持使用列表理解,我会说它既麻烦又没有必要,因为它会创建另一个列表,最终导致使用函数获取求和的相同方法。

问题的出现是因为python中的一行程序返回一个数组,它没有一个干净的方式来引用它自己正在创建的对象

你不能做一个可交换的和,你可以将数字相乘(但每一个都可以)

实现所需的最佳方法是使用其内置方法
sum

In [9]: sum(results)
Out[9]: 294

使用
y=sum(结果)
谢谢。你知道为什么我们不能在综合列表中使用“=”吗?
[total=total+x表示结果中的x]
不是综合列表。sintax错误的原因是
=
。使用
sum()
,因为它在列表理解中不是有效语法
In [2]: y = [x*x  for x in results]

In [3]: y
Out[3]: [22201, 0, 16384, 0, 0, 0, 1, 0, 0, 196, 0, 4]

In [9]: sum(results)
Out[9]: 294