简体   繁体   English

Python打印列表元素

[英]Python printing list element

I noticed that in the following snippet both approaches give the same result: 我注意到,在以下代码段中,两种方法均得出相同的结果:

>>> a = [1,2,3]
>>> print(a[0])
1
>>> print(a)[0]
1
>>> 

I was a bit surprised, as I would have expected print(a) to return a string, so then subscript 0 to just return the first character (Ie: [). 我有些惊讶,因为我期望print(a)返回一个字符串,所以下标0仅返回第一个字符(即:[])。 However, it seems Python interprets it as a list? 但是,似乎Python将其解释为列表?

Anybody able to clarify please? 有人可以澄清吗?

As mentioned, you're using python 2.x, where print is a statement, not a function — so print(a)[0] being parsed as print a[0] — treating braces as parsing priority modifier. 如前所述,您使用的是python 2.x,其中print是一条语句,而不是函数—因此, print(a)[0]被解析为print a[0] —将花括号视为解析优先级修饰符。

Important thing — print does not return what you're printing. 重要的事情- print 回你打印的东西。 It sends data to stream ( stdout by default). 它将数据发送到流(默认情况下为stdout )。 If you're using python 3.x (where print is a function) or use from __future__ import print_function — functions will send data to stream and return None as result. 如果您使用的是python 3.x(其中print是函数),或者from __future__ import print_function使用from __future__ import print_function —函数会将数据发送到流并返回None So print(a)[0] will resolve to "send content of a to stdout and return None[0] ", later will raise IndexError 因此, print(a)[0]将解析为“发送的内容a到标准输出和返回None[0] ”,以后将提高IndexError

As @jonrsharpe mentioned in the comment block, you're probably running python 2.x. 正如@jonrsharpe在注释块中提到的,您可能正在运行python2.x

print statement was replaced in python 3.x with print() function 在python 3.x中将print语句替换为print()函数

>>> print(a)[0]
[1, 2, 3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not subscriptable


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM