用Python的方式将列表分为第一部分和其余部分? [英] Pythonic way to split a list into first and rest?

查看:67
本文介绍了用Python的方式将列表分为第一部分和其余部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为在Python 3中我可以做到:

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

first, *rest = l

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

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

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

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

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

推荐答案

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)

这篇关于用Python的方式将列表分为第一部分和其余部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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