简体   繁体   English

如何在列表理解中修改Python列表的最后一个元素?

[英]How to modify last element of Python list in list comprehension?

I have a code segment like following which throws an invalid syntax error: 我有一个类似于以下的代码段,它将引发无效的语法错误:

lst = [0, 0, 0]
new_lst = [lst[-1] = i + 1 for i in range(3)]

Basically, I want new_lst to be list of lists, where every list will be lst but the last element changed. 基本上,我希望new_lst是列表列表,其中每个列表都是lst但最后一个元素已更改。 Any ideas how to do this in Python? 任何想法如何在Python中做到这一点?

You can only make assignments when they are stand-alone statements Ie not within a list comprehension. 您只能在它们是独立语句时(即不在列表理解范围内)进行分配。 Other examples of this would be in control statements like if s or for s 其他示例在控制语句中,例如iffor s

In [945]: lst = [0, 0, 0]

In [946]: new_lst = [lst[:-1] + [i + 1] for i in range(3)]

In [947]: new_lst
Out[947]: [[0, 0, 1], [0, 0, 2], [0, 0, 3]]

lst[:-1] takes every element from lst except for the last and [i + 1] will be appended to the end of the list lst[:-1]lst取出每个元素,除了最后一个元素, [i + 1]将附加到列表的末尾

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

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