How to ragged partition a list in Python?

2019-06-09 08:28发布

问题:

Is there a built-in Python function such that with

vals=[1,2,3,4,5]

then foo(vals,2) gives

[[1,2],[3,4],[5]]

I am looking for the behaviour that Wolfram Language gives with

Partition[Range@5, UpTo@2]
{{1, 2}, {3, 4}, {5}}

回答1:

This is built into neither the Python language itself nor its standard library, but might be what you are looking for functionality-wise:

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'

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)

Result:

[[1, 2], [3, 4], [5]]

If the iterable isn't sliceable, you can use chunked() from the same library instead of sliced.



回答2:

You can use a list comprehension with list indexing / slicing:

vals = [1,2,3,4,5]

def foo(v, j=2):
    return [v[i:i+j] for i in range(0, len(v), j)]

print(foo(vals, 2))

[[1, 2], [3, 4], [5]]

print(foo(vals, 3))

[[1, 2, 3], [4, 5]]


回答3:

Try this: 'n' is the subgroup size. 'l' is the list

def groups(l, n):
    for i in range(0, len(l), n):
        yield l[i:i + n]