将列表解压缩到元组的中间 [英] Unpack list into middle of a tuple

查看:100
本文介绍了将列表解压缩到元组的中间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个不确定的列表:

I have a list of uncertain size:

l = [...]

我想将此列表解压缩为具有其他值的元组,但以下操作失败:

And I want to unpack this list into a tuple that has other values, but the below fails:

t = ("AA", "B", *l, "C")

如何形成以下内容?

t = ("AA", "B", l[0], ..., l[:-1], "C")

最好只做一个切片[a:b]:

it would also be nice to do a slice [a:b] only:

t = ("AA", "B", l[a], ..., l[b], "C")

推荐答案

从python 3.5开始,您现在可以使用第一种方法:

As of python 3.5, you can now use your first approach:

>>> l = [1, 2, 3]
>>> t = ("AA", "B", *l, "C")
>>> t
('AA', 'B', 1, 2, 3, 'C')

您可以按预期使用切片:

You can use slices just as you'd expect:

>>> ("AA", "B", *l[:-1], "C")
('AA', 'B', 1, 2, 'C')

相关的PEP,以供参考: PEP448

The related PEP, for reference: PEP448

这篇关于将列表解压缩到元组的中间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆