作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
有没有一种 Python 的方式来解压缩第一个元素中的列表和单个命令中的“尾部”?
例如:
>> head, tail = **some_magic applied to** [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]
最佳答案
在 Python 3.x 下,你可以很好地做到这一点:
>>> head, *tail = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]
3.x 中的一个新特性是在解包中使用 *
运算符,表示任何额外的值。它在 PEP 3132 - Extended Iterable Unpacking 中有描述.这还具有处理任何可迭代的优点,而不仅仅是序列。
它也真的可读。
如 PEP 中所述,如果您想在 2.x 下执行等效操作(而不可能制作临时列表),您必须这样做:
it = iter(iterable)
head, tail = next(it), list(it)
正如评论中所指出的,这也提供了获取 head
的默认值而不是引发异常的机会。如果你想要这种行为,next()
接受带有默认值的可选第二个参数,因此如果没有 head 元素,next(it, None)
会给你 None
。
当然,如果您正在处理列表,那么不使用 3.x 语法的最简单方法是:
head, tail = seq[0], seq[1:]
关于python - 头尾在一条线上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10532473/
我是一名优秀的程序员,十分优秀!