Python:列表理解无效语法

2024-04-24 08:13:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着在一行中重现这个循环:

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  

我错过了什么?非常感谢。你知道吗


Tags: infor错误resultstotalprintsyntaxinvalid
2条回答

您只需要使用函数:

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

或者

from functools import reduce
results = reduce(lambda x, y: x + y, results)
print(results)

如果你坚持使用列表理解,我会说它是麻烦和不必要的,因为它将创建另一个列表,最终导致同样的方法使用函数来获得总和。你知道吗

问题的出现是因为python中的一行程序返回一个数组,它没有一个干净的方法来引用它自己创建的对象。你知道吗

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

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]

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

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

相关问题 更多 >