Convert a list into chunks of increasing size
How could I convert a list into a nested list with increasing size of the sublists?
For example,
from
[1, 2, 3, 4, 5, 6]
to
[[1], [2, 3], [4, 5, 6]]
python list
add a comment |
How could I convert a list into a nested list with increasing size of the sublists?
For example,
from
[1, 2, 3, 4, 5, 6]
to
[[1], [2, 3], [4, 5, 6]]
python list
2
that supposes that the length of the list is of the form (n+1)*n // 2 for starters. Is there something you tried?
– Jean-François Fabre
Nov 18 '18 at 19:43
And what have you tried so far?
– schwobaseggl
Nov 18 '18 at 19:43
1
By writing some code. How do you decide the length of each sub-array? Would a list[2,3,4]
get split in[[2,3],[4]]
? If the sequence of lengths is 1,2,3... what happens with the last element if these do not add up?
– usr2564301
Nov 18 '18 at 19:45
this could help (with adaptation): stackoverflow.com/questions/312443/…
– Jean-François Fabre
Nov 18 '18 at 19:45
Welcome to SO! It's unclear how odd-length lists should be handled. Please clarify.
– ggorlen
Nov 18 '18 at 20:06
add a comment |
How could I convert a list into a nested list with increasing size of the sublists?
For example,
from
[1, 2, 3, 4, 5, 6]
to
[[1], [2, 3], [4, 5, 6]]
python list
How could I convert a list into a nested list with increasing size of the sublists?
For example,
from
[1, 2, 3, 4, 5, 6]
to
[[1], [2, 3], [4, 5, 6]]
python list
python list
edited Nov 18 '18 at 20:01
timgeb
50.8k116493
50.8k116493
asked Nov 18 '18 at 19:41
IvanIvan
4
4
2
that supposes that the length of the list is of the form (n+1)*n // 2 for starters. Is there something you tried?
– Jean-François Fabre
Nov 18 '18 at 19:43
And what have you tried so far?
– schwobaseggl
Nov 18 '18 at 19:43
1
By writing some code. How do you decide the length of each sub-array? Would a list[2,3,4]
get split in[[2,3],[4]]
? If the sequence of lengths is 1,2,3... what happens with the last element if these do not add up?
– usr2564301
Nov 18 '18 at 19:45
this could help (with adaptation): stackoverflow.com/questions/312443/…
– Jean-François Fabre
Nov 18 '18 at 19:45
Welcome to SO! It's unclear how odd-length lists should be handled. Please clarify.
– ggorlen
Nov 18 '18 at 20:06
add a comment |
2
that supposes that the length of the list is of the form (n+1)*n // 2 for starters. Is there something you tried?
– Jean-François Fabre
Nov 18 '18 at 19:43
And what have you tried so far?
– schwobaseggl
Nov 18 '18 at 19:43
1
By writing some code. How do you decide the length of each sub-array? Would a list[2,3,4]
get split in[[2,3],[4]]
? If the sequence of lengths is 1,2,3... what happens with the last element if these do not add up?
– usr2564301
Nov 18 '18 at 19:45
this could help (with adaptation): stackoverflow.com/questions/312443/…
– Jean-François Fabre
Nov 18 '18 at 19:45
Welcome to SO! It's unclear how odd-length lists should be handled. Please clarify.
– ggorlen
Nov 18 '18 at 20:06
2
2
that supposes that the length of the list is of the form (n+1)*n // 2 for starters. Is there something you tried?
– Jean-François Fabre
Nov 18 '18 at 19:43
that supposes that the length of the list is of the form (n+1)*n // 2 for starters. Is there something you tried?
– Jean-François Fabre
Nov 18 '18 at 19:43
And what have you tried so far?
– schwobaseggl
Nov 18 '18 at 19:43
And what have you tried so far?
– schwobaseggl
Nov 18 '18 at 19:43
1
1
By writing some code. How do you decide the length of each sub-array? Would a list
[2,3,4]
get split in [[2,3],[4]]
? If the sequence of lengths is 1,2,3... what happens with the last element if these do not add up?– usr2564301
Nov 18 '18 at 19:45
By writing some code. How do you decide the length of each sub-array? Would a list
[2,3,4]
get split in [[2,3],[4]]
? If the sequence of lengths is 1,2,3... what happens with the last element if these do not add up?– usr2564301
Nov 18 '18 at 19:45
this could help (with adaptation): stackoverflow.com/questions/312443/…
– Jean-François Fabre
Nov 18 '18 at 19:45
this could help (with adaptation): stackoverflow.com/questions/312443/…
– Jean-François Fabre
Nov 18 '18 at 19:45
Welcome to SO! It's unclear how odd-length lists should be handled. Please clarify.
– ggorlen
Nov 18 '18 at 20:06
Welcome to SO! It's unclear how odd-length lists should be handled. Please clarify.
– ggorlen
Nov 18 '18 at 20:06
add a comment |
4 Answers
4
active
oldest
votes
I'd do this with islices over an iterator of the original list. This way I can just specifiy the number of elements to take without having to worry at which position I am currently at. (In addition, the following code works with any iterable.)
def increasing_chunks(iterable):
it = iter(iterable)
i = 1
while True:
chunk = list(islice(it, i))
if not chunk:
break
yield chunk
i += 1
The last chunk might be truncated to whatever amount of elements the iterator had left.
Demo:
>>> list(increasing_chunks([1, 2, 3, 4, 5, 6]))
[[1], [2, 3], [4, 5, 6]]
>>> list(increasing_chunks([1, 2, 3, 4, 5, 6, 7, 8]))
[[1], [2, 3], [4, 5, 6], [7, 8]]
If you want to discard truncated chunks, adjust the code as follows:
def increasing_chunks_strict(iterable):
it = iter(iterable)
i = 1
while True:
chunk = list(islice(it, i))
if len(chunk) < i:
break
yield chunk
i += 1
Now, truncated chunks are not included in the result.
>>> list(increasing_chunks_strict([1, 2, 3, 4, 5, 6]))
[[1], [2, 3], [4, 5, 6]]
>>> list(increasing_chunks_strict([1, 2, 3, 4, 5, 6, 7, 8]))
[[1], [2, 3], [4, 5, 6]]
add a comment |
As a follow up to timgeb's solution, without itertools
, you need to keep track of the index:
l = [1, 2, 3, 4, 5, 6]
i, slice_length = 0, 1
result =
while i < len(l):
result.append(l[i:i + slice_length])
i += slice_length
slice_length += 1
print(result)
# [[1], [2, 3], [4, 5, 6]]
add a comment |
Several itertools
and enumerate
to the rescue:
from itertools import count, accumulate as acc, takewhile as tw
lst = [1, 2, 3, 4, 5, 6]
[lst[c:c+i] for i, c in enumerate(tw(lambda x: x < len(lst), acc(count())), 1)]
# [[1], [2, 3], [4, 5, 6]]
add a comment |
Assuming that you list length has the correct length for the last chunk to have the correct size, you can use list sum
, range
and list comprehension to solve your problem in few lines:
l = [1, 2, 3, 4, 5, 6]
slices = range(1, (len(l) + 1)/2 + 1)
result = [l[sum(slices[:s-1]):sum(slices[:s-1])+s] for s in slices]
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53364762%2fconvert-a-list-into-chunks-of-increasing-size%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
I'd do this with islices over an iterator of the original list. This way I can just specifiy the number of elements to take without having to worry at which position I am currently at. (In addition, the following code works with any iterable.)
def increasing_chunks(iterable):
it = iter(iterable)
i = 1
while True:
chunk = list(islice(it, i))
if not chunk:
break
yield chunk
i += 1
The last chunk might be truncated to whatever amount of elements the iterator had left.
Demo:
>>> list(increasing_chunks([1, 2, 3, 4, 5, 6]))
[[1], [2, 3], [4, 5, 6]]
>>> list(increasing_chunks([1, 2, 3, 4, 5, 6, 7, 8]))
[[1], [2, 3], [4, 5, 6], [7, 8]]
If you want to discard truncated chunks, adjust the code as follows:
def increasing_chunks_strict(iterable):
it = iter(iterable)
i = 1
while True:
chunk = list(islice(it, i))
if len(chunk) < i:
break
yield chunk
i += 1
Now, truncated chunks are not included in the result.
>>> list(increasing_chunks_strict([1, 2, 3, 4, 5, 6]))
[[1], [2, 3], [4, 5, 6]]
>>> list(increasing_chunks_strict([1, 2, 3, 4, 5, 6, 7, 8]))
[[1], [2, 3], [4, 5, 6]]
add a comment |
I'd do this with islices over an iterator of the original list. This way I can just specifiy the number of elements to take without having to worry at which position I am currently at. (In addition, the following code works with any iterable.)
def increasing_chunks(iterable):
it = iter(iterable)
i = 1
while True:
chunk = list(islice(it, i))
if not chunk:
break
yield chunk
i += 1
The last chunk might be truncated to whatever amount of elements the iterator had left.
Demo:
>>> list(increasing_chunks([1, 2, 3, 4, 5, 6]))
[[1], [2, 3], [4, 5, 6]]
>>> list(increasing_chunks([1, 2, 3, 4, 5, 6, 7, 8]))
[[1], [2, 3], [4, 5, 6], [7, 8]]
If you want to discard truncated chunks, adjust the code as follows:
def increasing_chunks_strict(iterable):
it = iter(iterable)
i = 1
while True:
chunk = list(islice(it, i))
if len(chunk) < i:
break
yield chunk
i += 1
Now, truncated chunks are not included in the result.
>>> list(increasing_chunks_strict([1, 2, 3, 4, 5, 6]))
[[1], [2, 3], [4, 5, 6]]
>>> list(increasing_chunks_strict([1, 2, 3, 4, 5, 6, 7, 8]))
[[1], [2, 3], [4, 5, 6]]
add a comment |
I'd do this with islices over an iterator of the original list. This way I can just specifiy the number of elements to take without having to worry at which position I am currently at. (In addition, the following code works with any iterable.)
def increasing_chunks(iterable):
it = iter(iterable)
i = 1
while True:
chunk = list(islice(it, i))
if not chunk:
break
yield chunk
i += 1
The last chunk might be truncated to whatever amount of elements the iterator had left.
Demo:
>>> list(increasing_chunks([1, 2, 3, 4, 5, 6]))
[[1], [2, 3], [4, 5, 6]]
>>> list(increasing_chunks([1, 2, 3, 4, 5, 6, 7, 8]))
[[1], [2, 3], [4, 5, 6], [7, 8]]
If you want to discard truncated chunks, adjust the code as follows:
def increasing_chunks_strict(iterable):
it = iter(iterable)
i = 1
while True:
chunk = list(islice(it, i))
if len(chunk) < i:
break
yield chunk
i += 1
Now, truncated chunks are not included in the result.
>>> list(increasing_chunks_strict([1, 2, 3, 4, 5, 6]))
[[1], [2, 3], [4, 5, 6]]
>>> list(increasing_chunks_strict([1, 2, 3, 4, 5, 6, 7, 8]))
[[1], [2, 3], [4, 5, 6]]
I'd do this with islices over an iterator of the original list. This way I can just specifiy the number of elements to take without having to worry at which position I am currently at. (In addition, the following code works with any iterable.)
def increasing_chunks(iterable):
it = iter(iterable)
i = 1
while True:
chunk = list(islice(it, i))
if not chunk:
break
yield chunk
i += 1
The last chunk might be truncated to whatever amount of elements the iterator had left.
Demo:
>>> list(increasing_chunks([1, 2, 3, 4, 5, 6]))
[[1], [2, 3], [4, 5, 6]]
>>> list(increasing_chunks([1, 2, 3, 4, 5, 6, 7, 8]))
[[1], [2, 3], [4, 5, 6], [7, 8]]
If you want to discard truncated chunks, adjust the code as follows:
def increasing_chunks_strict(iterable):
it = iter(iterable)
i = 1
while True:
chunk = list(islice(it, i))
if len(chunk) < i:
break
yield chunk
i += 1
Now, truncated chunks are not included in the result.
>>> list(increasing_chunks_strict([1, 2, 3, 4, 5, 6]))
[[1], [2, 3], [4, 5, 6]]
>>> list(increasing_chunks_strict([1, 2, 3, 4, 5, 6, 7, 8]))
[[1], [2, 3], [4, 5, 6]]
edited Nov 18 '18 at 20:10
answered Nov 18 '18 at 19:48
timgebtimgeb
50.8k116493
50.8k116493
add a comment |
add a comment |
As a follow up to timgeb's solution, without itertools
, you need to keep track of the index:
l = [1, 2, 3, 4, 5, 6]
i, slice_length = 0, 1
result =
while i < len(l):
result.append(l[i:i + slice_length])
i += slice_length
slice_length += 1
print(result)
# [[1], [2, 3], [4, 5, 6]]
add a comment |
As a follow up to timgeb's solution, without itertools
, you need to keep track of the index:
l = [1, 2, 3, 4, 5, 6]
i, slice_length = 0, 1
result =
while i < len(l):
result.append(l[i:i + slice_length])
i += slice_length
slice_length += 1
print(result)
# [[1], [2, 3], [4, 5, 6]]
add a comment |
As a follow up to timgeb's solution, without itertools
, you need to keep track of the index:
l = [1, 2, 3, 4, 5, 6]
i, slice_length = 0, 1
result =
while i < len(l):
result.append(l[i:i + slice_length])
i += slice_length
slice_length += 1
print(result)
# [[1], [2, 3], [4, 5, 6]]
As a follow up to timgeb's solution, without itertools
, you need to keep track of the index:
l = [1, 2, 3, 4, 5, 6]
i, slice_length = 0, 1
result =
while i < len(l):
result.append(l[i:i + slice_length])
i += slice_length
slice_length += 1
print(result)
# [[1], [2, 3], [4, 5, 6]]
answered Nov 18 '18 at 20:12
sliderslider
8,29311130
8,29311130
add a comment |
add a comment |
Several itertools
and enumerate
to the rescue:
from itertools import count, accumulate as acc, takewhile as tw
lst = [1, 2, 3, 4, 5, 6]
[lst[c:c+i] for i, c in enumerate(tw(lambda x: x < len(lst), acc(count())), 1)]
# [[1], [2, 3], [4, 5, 6]]
add a comment |
Several itertools
and enumerate
to the rescue:
from itertools import count, accumulate as acc, takewhile as tw
lst = [1, 2, 3, 4, 5, 6]
[lst[c:c+i] for i, c in enumerate(tw(lambda x: x < len(lst), acc(count())), 1)]
# [[1], [2, 3], [4, 5, 6]]
add a comment |
Several itertools
and enumerate
to the rescue:
from itertools import count, accumulate as acc, takewhile as tw
lst = [1, 2, 3, 4, 5, 6]
[lst[c:c+i] for i, c in enumerate(tw(lambda x: x < len(lst), acc(count())), 1)]
# [[1], [2, 3], [4, 5, 6]]
Several itertools
and enumerate
to the rescue:
from itertools import count, accumulate as acc, takewhile as tw
lst = [1, 2, 3, 4, 5, 6]
[lst[c:c+i] for i, c in enumerate(tw(lambda x: x < len(lst), acc(count())), 1)]
# [[1], [2, 3], [4, 5, 6]]
answered Nov 18 '18 at 20:01
schwobasegglschwobaseggl
37.2k32442
37.2k32442
add a comment |
add a comment |
Assuming that you list length has the correct length for the last chunk to have the correct size, you can use list sum
, range
and list comprehension to solve your problem in few lines:
l = [1, 2, 3, 4, 5, 6]
slices = range(1, (len(l) + 1)/2 + 1)
result = [l[sum(slices[:s-1]):sum(slices[:s-1])+s] for s in slices]
add a comment |
Assuming that you list length has the correct length for the last chunk to have the correct size, you can use list sum
, range
and list comprehension to solve your problem in few lines:
l = [1, 2, 3, 4, 5, 6]
slices = range(1, (len(l) + 1)/2 + 1)
result = [l[sum(slices[:s-1]):sum(slices[:s-1])+s] for s in slices]
add a comment |
Assuming that you list length has the correct length for the last chunk to have the correct size, you can use list sum
, range
and list comprehension to solve your problem in few lines:
l = [1, 2, 3, 4, 5, 6]
slices = range(1, (len(l) + 1)/2 + 1)
result = [l[sum(slices[:s-1]):sum(slices[:s-1])+s] for s in slices]
Assuming that you list length has the correct length for the last chunk to have the correct size, you can use list sum
, range
and list comprehension to solve your problem in few lines:
l = [1, 2, 3, 4, 5, 6]
slices = range(1, (len(l) + 1)/2 + 1)
result = [l[sum(slices[:s-1]):sum(slices[:s-1])+s] for s in slices]
answered Nov 18 '18 at 20:07
Aurora WangAurora Wang
723316
723316
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53364762%2fconvert-a-list-into-chunks-of-increasing-size%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
that supposes that the length of the list is of the form (n+1)*n // 2 for starters. Is there something you tried?
– Jean-François Fabre
Nov 18 '18 at 19:43
And what have you tried so far?
– schwobaseggl
Nov 18 '18 at 19:43
1
By writing some code. How do you decide the length of each sub-array? Would a list
[2,3,4]
get split in[[2,3],[4]]
? If the sequence of lengths is 1,2,3... what happens with the last element if these do not add up?– usr2564301
Nov 18 '18 at 19:45
this could help (with adaptation): stackoverflow.com/questions/312443/…
– Jean-François Fabre
Nov 18 '18 at 19:45
Welcome to SO! It's unclear how odd-length lists should be handled. Please clarify.
– ggorlen
Nov 18 '18 at 20:06