如何在Python中对列表进行破烂的分割? [英] How to ragged partition a list in Python?
问题描述
是否有内置的Python函数,例如
Is there a built-in Python function such that with
vals=[1,2,3,4,5]
然后foo(vals,2)
给出
[[1,2],[3,4],[5]]
我正在寻找Wolfram语言所赋予的行为
I am looking for the behaviour that Wolfram Language gives with
Partition[Range@5, UpTo@2]
{{1, 2}, {3, 4}, {5}}
推荐答案
这既没有内置在Python语言本身,也没有内置在其标准库中,但是可能是您在功能方面寻求的:
This is built into neither the Python language itself nor its standard library, but might be what you are looking for functionality-wise:
安装第三方库更多itertools (不要与itertools
模块( 是Python标准库的一部分),例如与
Install the third-party-library more-itertools (not to be confused with the itertools
module, which is part of the Python standard library), e.g. with
pipenv install 'more-itertools >= 2.4'
然后,您可以使用函数sliced()
它提供:
Then you can use the function sliced()
it provides:
from more_itertools import sliced
vals = [1,2,3,4,5]
slices = list(sliced(vals, 2))
print(slices)
结果:
[[1, 2], [3, 4], [5]]
如果迭代器不可切片,则可以使用 chunked()
来自同一库,而不是切片.
If the iterable isn't sliceable, you can use chunked()
from the same library instead of sliced.
这篇关于如何在Python中对列表进行破烂的分割?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!