将列表拆分为第一个和休息的 Pythonic 方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3513947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:29:52  来源:igfitidea点击:

Pythonic way to split a list into first and rest?

pythonlistsplit

提问by Shawn

I think in Python 3 I'll be able to do:

我认为在 Python 3 中我将能够做到:

first, *rest = l

which is exactly what I want, but I'm using 2.6. For now I'm doing:

这正是我想要的,但我使用的是 2.6。现在我正在做:

first = l[0]
rest = l[1:]

This is fine, but I was just wondering if there's something more elegant.

这很好,但我只是想知道是否有更优雅的东西。

采纳答案by Shawn

first, rest = l[0], l[1:]

Basically the same, except that it's a oneliner. Tuple assigment rocks.

基本上是一样的,只是它是一个单线。元组分配岩石。

This is a bit longer and less obvious, but generalized for all iterables (instead of being restricted to sliceables):

这有点长且不太明显,但适用于所有可迭代对象(而不是仅限于切片):

i = iter(l)
first = next(i) # i.next() in older versions
rest = list(i)

回答by Olivier '?lbaum' Scherler

You can do

你可以做

first = l.pop(0)

and then lwill be the rest. It modifies your original list, though, so maybe it's not what you want.

然后l就是剩下的了。但是,它会修改您的原始列表,因此它可能不是您想要的。

回答by FGH

I would suggest:

我会建议:

first, remainder = l.split(None, maxsplit=1)

回答by kriss

Yet another one, working with python 2.7. Just use an intermediate function. Logical as the new behavior mimics what happened for functions parameters passing.

另一个,使用 python 2.7。只需使用一个中间函数。合乎逻辑,因为新行为模仿了函数参数传递时发生的情况。

li = [1, 2, 3]
first, rest = (lambda x, *y: (x, y))(*li)