无法在列表理解中使用* = python运算符 [英] Unable to use *= python operator in list comprehension
本文介绍了无法在列表理解中使用* = python运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不确定为什么不能在列表理解中使用*=
运算符,而在for
循环中使用它会很好吗?
I'm not sure why I'm unable to use the *=
operator in a list comprehension, when using it in a for
loop is fine?
def funcLC(l):
ans = 1
[ans *= x for x in l if x < 0]
return ans
SyntaxError: invalid syntax
def funcFor(l):
ans = 1
for x in l:
if x < 0:
start *= x
return ans
推荐答案
赋值运算符(及其上的所有变体)在Python中形成一个语句,而不是一个表达式 .不幸的是,列表推导(以及集合,字典和生成器等其他推导)仅支持表达式.
The assignment operator (and all variations on it) forms a statement in Python, not an expression. Unfortunately, list comprehensions (and other comprehensions, like set, dictionary and generators) only support expressions.
这篇关于无法在列表理解中使用* = python运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文