列表理解:为什么这是语法错误? [英] List Comprehension: why is this a syntax error?
本文介绍了列表理解:为什么这是语法错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么下面的列表理解中的print(x)
在这里无效(SyntaxError
)?
Why is print(x)
here not valid (SyntaxError
) in the following list-comprehension?
my_list=[1,2,3]
[print(my_item) for my_item in my_list]
与之相反,以下内容不会出现语法错误:
To contrast - the following doesn't give a syntax error:
def my_func(x):
print(x)
[my_func(my_item) for my_item in my_list]
推荐答案
因为print不是函数,而是语句,所以不能在表达式中包含它们.如果您使用普通的Python 2语法,这将变得更加明显:
Because print is not a function, it's a statement, and you can't have them in expressions. This gets more obvious if you use normal Python 2 syntax:
my_list=[1,2,3]
[print my_item for my_item in my_list]
那看起来不太正确. :)围绕my_item的括号会欺骗您.
That doesn't look quite right. :) The parenthesizes around my_item tricks you.
这在Python 3 btw中有所改变,其中print 是一个函数,您的代码可以正常工作.
This has changed in Python 3, btw, where print is a function, where your code works just fine.
这篇关于列表理解:为什么这是语法错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文