列表理解:为什么这是一个语法错误?

时间:2022-01-12 23:01:40

Why is print(x) here not valid (SyntaxError) in the following list-comprehension?

为什么这里的print(x)在以下列表理解中无效(SyntaxError) ?

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]

3 个解决方案

#1


53  

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:

因为print不是函数,它是一个语句,你不能在表达式中使用它们。如果使用普通的Python 2语法,这一点就变得更加明显:

my_list=[1,2,3]
[print my_item for my_item in my_list]

That doesn't look quite right. :) The parenthesizes around my_item tricks you.

这看起来不太对。:) my_item周围的括号欺骗了您。

This has changed in Python 3, btw, where print is a function, where your code works just fine.

顺便说一句,这在Python 3中已经发生了变化,其中print是一个函数,您的代码可以正常工作。

#2


6  

It's a syntax error because print is not a function. It's a statement. Since you obviously don't care about the return value from print (since it has none), just write the normal loop:

这是一个语法错误,因为print不是函数。这是一个声明。既然您显然不关心打印的返回值(因为它没有),只需编写正常的循环:

for my_item in my_list:
    print my_item

#3


6  

list comprehension are designed to create a list. So using print inside it will give an error no-matter we use print() or print in 2.7 or 3.x. The code

列表理解是用来创建列表的。所以在里面使用print就会产生一个错误无论我们使用print()还是3。x中的print。的代码

[my_item for my_item in my_list] 

makes a new object of type list.

创建类型列表的新对象。

print [my_item for my_item in my_list]

prints out this new list as a whole

把这个新列表作为一个整体打印出来

refer : here

参考:

#1


53  

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:

因为print不是函数,它是一个语句,你不能在表达式中使用它们。如果使用普通的Python 2语法,这一点就变得更加明显:

my_list=[1,2,3]
[print my_item for my_item in my_list]

That doesn't look quite right. :) The parenthesizes around my_item tricks you.

这看起来不太对。:) my_item周围的括号欺骗了您。

This has changed in Python 3, btw, where print is a function, where your code works just fine.

顺便说一句,这在Python 3中已经发生了变化,其中print是一个函数,您的代码可以正常工作。

#2


6  

It's a syntax error because print is not a function. It's a statement. Since you obviously don't care about the return value from print (since it has none), just write the normal loop:

这是一个语法错误,因为print不是函数。这是一个声明。既然您显然不关心打印的返回值(因为它没有),只需编写正常的循环:

for my_item in my_list:
    print my_item

#3


6  

list comprehension are designed to create a list. So using print inside it will give an error no-matter we use print() or print in 2.7 or 3.x. The code

列表理解是用来创建列表的。所以在里面使用print就会产生一个错误无论我们使用print()还是3。x中的print。的代码

[my_item for my_item in my_list] 

makes a new object of type list.

创建类型列表的新对象。

print [my_item for my_item in my_list]

prints out this new list as a whole

把这个新列表作为一个整体打印出来

refer : here

参考: