简体   繁体   English

在Python中访问列表初始化内的元素

[英]Accessing element inside list initialization in Python

In Python 3 is it possible to access a list element inside this list initialization? 在Python 3中是否可以访问此列表初始化中的列表元素? I think, it's impossible, but I'm interested just in case it is. 我想,这是不可能的,但我对它的情况感兴趣。

For example, something like this: 例如,像这样:

lst = [0, 1, 2, 3] + lst[0]

or 要么

lst = [0, 1, 2, 3, lst[0]]

Thank you in advance! 先感谢您!

No. The entire right-hand side of the assignment is evaluated before it is assigned to the name on the left. 在编号分配到左侧名称之前,将评估分配的整个右侧。 So you can't use lst on the right because lst doesn't exist until after the right-hand side has finished evaluating. 所以你不能在右边使用lst ,因为在右手边完成评估之后, lst才会存在。

You still don't have a name for the part of lst you want to access, so you cannot access it. 你仍然不具备的部分名称lst您要访问的,所以你不能访问它。

But defining a name is trivial: 但定义一个名称是微不足道的:

left_lst = [1, 2, 3]
lst = left_lst + left_lst[2:3]

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

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