how can i make this combination like
array = [1,2,3,4,5,6,7,8,9]
combination
[1,2,3]
[4,5,6]
[7,8,9]
how can i make this combination like
array = [1,2,3,4,5,6,7,8,9]
combination
[1,2,3]
[4,5,6]
[7,8,9]
There are many ways, all depending on what you intend to do. A simple way is to slice.
array[:3], array[3:6], array[6:]
or use a comprehenion, but you might prefer a third-party tool more-itertools.chunked()
.
list(more_itertools.chucked(array, 3))
Install the package: > pip install more-itertools
.
I sent this response on Wednesday, two days ago, but it seems to have
vanished into the aether. Let me try again:
You can try something like this:
>>> array = [1,2,3,4,5,6,7,8,9]
>>> for i in range(len(array)//3):
... print(array[i*3:i*3 + 3])
...
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Another possibility is the “grouper” recipe in the itertools
documentation: