头部和尾部在一条线上

时间:2012-05-10 10:52:22

标签: python list tail head

是否有一种pythonic方法来解压缩第一个元素中的列表和单个命令中的“tail”?

例如:

>> 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]

5 个答案:

答案 0 :(得分:165)

在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 = it.next()
tail = list(it)

当然,如果您正在处理列表,那么没有3.x语法的最简单方法是:

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

答案 1 :(得分:35)

>>> mylist = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> head, tail = mylist[0], mylist[1:]
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]

答案 2 :(得分:8)

对于head,tail操作的O(1)复杂性,您应该使用deque

以下方式:

from collections import deque
l = deque([1,2,3,4,5,6,7,8,9])
head, tail = l.popleft(), l

当您必须遍历列表中的所有元素时,它非常有用。例如,在合并排序中的天真合并2个分区。

答案 3 :(得分:2)

Python 2,使用lambda

>>> head, tail = (lambda lst: (lst[0], lst[1:]))([1, 1, 2, 3, 5, 8, 13, 21, 34, 55])
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]

答案 4 :(得分:1)

Python 2 solution from @GarethLatty的基础上,以下是在Python 2中获得不包含中间变量的单行等效项的方法。

t=iter([1, 1, 2, 3, 5, 8, 13, 21, 34, 55]);h,t = [(h,list(t)) for h in t][0]

如果您需要它是防异常的(即支持空列表),请添加:

t=iter([]);h,t = ([(h,list(t)) for h in t]+[(None,[])])[0]

如果要在不使用分号的情况下进行操作,请使用:

h,t = ([(h,list(t)) for t in [iter([1,2,3,4])] for h in t]+[(None,[])])[0]
相关问题