简体   繁体   English

Python:将元组转换为列表并插入() - 在一个表达式中?

[英]Python: Convert tuple to list and insert() - in one expression?

I am trying to do something like this:我正在尝试做这样的事情:

my_list = list((1,2,3)).insert(0,0)

Is there a way to do that in one expression?有没有办法在一个表达式中做到这一点?

PS I am not trying to be economic with my lines, I'm just curious is that possible and how would one do it in python. PS我并不是想用我的台词经济,我只是好奇这是否可能以及如何在python中做到这一点。

If you are on python 3.8+ this is doable如果您使用的是 python 3.8+,这是可行的

>>> (my_list:=list((1,2,3))).insert(0,0)
>>> my_list
[0, 1, 2, 3]

One slightly naive way is the following:一种稍微幼稚的方法如下:

a = [0] + list((1,2,3))

.insert() (same as .append() , .extend() , etc) modifies the list but don't actually return anything, that's why you can't use them in a chained operation. .insert() (与.append().extend()等相同)修改列表但实际上不返回任何内容,这就是您不能在链式操作中使用它们的原因。 See the answer here about why this happens as a Python design choice.请参阅此处答案,了解为什么会出现这种情况作为 Python 设计选择。

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

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