Python:从列表中获取多个列表
可能的重复:
如何将列表均匀分割Python 中的块大小?
嗨,
我想将一个列表拆分为多个长度为 x 元素的列表,例如:
a = (1, 2, 3, 4, 5)
并获取:
乙 = ( (1,2), (3,4), (5,) )
如果长度设置为 2 或:
乙 = ( (1,2,3), (4,5) )
如果长度等于 3 ...
有没有好的方法来写这个?否则我认为最好的方法是使用迭代器来编写它......
Possible Duplicate:
How do you split a list into evenly sized chunks in Python?
Hi,
I would like to split a list in many list of a length of x elements, like:
a = (1, 2, 3, 4, 5)
and get :
b = (
(1,2),
(3,4),
(5,)
)
if the length is set to 2 or :
b = (
(1,2,3),
(4,5)
)
if the length is equal to 3 ...
Is there a nice way to write this ? Otherwise I think the best way is to write it using an iterator ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我就是这样做的。迭代,但在列表理解中。注意类型是混合的;这可能是所希望的,也可能不是所希望的。
用法:
当然,如果您愿意,您也可以轻松地使其生成
tuple
- 将列表理解[...]
替换为tuple(... )
。您还可以将seq[i:i + length]
替换为tuple(seq[i:i + length])
或list(seq[i:i + length])
使其返回固定类型。Here's how I'd do it. Iteration, but in a list comprehension. Note the type gets mixed; this may or may not be desired.
Usage:
Of course, you can easily make it produce a
tuple
too if you want - replace the list comprehension[...]
withtuple(...)
. You could also replaceseq[i:i + length]
withtuple(seq[i:i + length])
orlist(seq[i:i + length])
to make it return a fixed type.itertools 模块文档。阅读它,学习它,喜欢它。
具体来说,从食谱部分:
给出:
这并不完全是你想要的......你不希望其中有
None
......所以。快速修复:如果您不喜欢每次都输入列表理解,我们可以将其逻辑移至函数中:
给出:
完成。
The itertools module documentation. Read it, learn it, love it.
Specifically, from the recipes section:
Which gives:
which isn't quite what you want...you don't want the
None
in there...so. a quick fix:If you don't like typing the list comprehension every time, we can move its logic into the function:
Which gives:
Done.
来自 itertools 模块上的 python 文档:
示例:
From the python docs on the itertools module:
Example: