头尾一条线 [英] Head and tail in one line

查看:88
本文介绍了头尾一条线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种Python方法可以在单个命令中解压缩第一个元素和"tail"中的列表?

Is there a pythonic way to unpack a list in the first element and the "tail" in a single command?

例如:

>> 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中,您可以很好地做到这一点:

Under Python 3.x, you can do this nicely:

>>> 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-扩展的可迭代拆包中对此进行了描述.这还具有处理任何可迭代的,而不仅仅是序列的优点.

A new feature in 3.x is to use the * operator in unpacking, to mean any extra values. It is described in PEP 3132 - Extended Iterable Unpacking. This also has the advantage of working on any iterable, not just sequences.

它也是真正可读的.

如PEP中所述,如果要在2.x下执行等效操作(可能不会创建临时列表),则必须执行以下操作:

As described in the PEP, if you want to do the equivalent under 2.x (without potentially making a temporary list), you have to do this:

it = iter(iterable)
head, tail = next(it), list(it)

如注释中所述,

这也为获取head的默认值提供了机会,而不是引发异常.如果您想要这种行为, next() 可以使用第二个可选参数默认值,因此如果没有head元素,则next(it, None)将为您提供None.

As noted in the comments, this also provides an opportunity to get a default value for head rather than throwing an exception. If you want this behaviour, next() takes an optional second argument with a default value, so next(it, None) would give you None if there was no head element.

自然地,如果您正在处理列表,则不使用3.x语法的最简单方法是:

Naturally, if you are working on a list, the easiest way without the 3.x syntax is:

head, tail = seq[0], seq[1:]

这篇关于头尾一条线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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