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