Python返回几个值以添加到列表中间

Vin*_*243 2 python

是否可以创建一个返回如下几个元素的函数:

def foo():
  return 'b', 'c', 'd'

print ['a', foo(), 'e'] # ['a', 'b', 'c', 'd', 'e']
Run Code Online (Sandbox Code Playgroud)

我试过这个,但它不起作用

Mar*_*ers 9

您可以使用切片分配将序列插入到列表中:

bar = ['a', 'e']
bar[1:1] = foo()
print bar
Run Code Online (Sandbox Code Playgroud)

请注意,切片基本上是空的; bar[1:1]'a'和之间的空列表'e'.

要在Python 2中的一行执行此操作,需要连接:

['a'] + list(foo()) + ['e']
Run Code Online (Sandbox Code Playgroud)

如果您要升级到Python 3.5,则可以使用*解压缩:

print(['a', *foo(), 'e'])
Run Code Online (Sandbox Code Playgroud)

其他开箱推广什么在Python 3.5的新功能.

演示(使用Python 3):

>>> def foo():
...     return 'b', 'c', 'd'
...
>>> bar = ['a', 'e']
>>> bar[1:1] = foo()
>>> bar
['a', 'b', 'c', 'd', 'e']
>>> ['a'] + list(foo()) + ['e']
['a', 'b', 'c', 'd', 'e']
>>> ['a', *foo(), 'e']
['a', 'b', 'c', 'd', 'e']
Run Code Online (Sandbox Code Playgroud)