Reputation: 31
I have this list:
newlis = [[6], [3], [4], [10], [9], [1], [2], [5], [7], [0], [8]]
I want to merge every two consecutive sublists (whether they are odd or even). I tried this code:
while len(newlis) != 1:
lis1=[(a + b) for a, b in zip(newlis[::2], newlis[1::2])]
newlis=lis1
print newlis
The result was: [[6, 3], [4, 10], [9, 1], [2, 5], [7, 0]]
How can I modify the code that it will print [[6, 3], [4, 10], [9, 1], [2, 5], [7, 0], [8]]
instead?
Upvotes: 0
Views: 121
Reputation: 19717
If you do not want to import any library, you can use this simple one liner:
result = [sum(newlis[i:i+2], []) for i in range(0, len(newlis), 2)]
Upvotes: 0
Reputation: 42778
Use itertools.groupby
:
>>> [[w for _, q in k for w in q] for _, k in itertools.groupby(enumerate(newlis), lambda (a,b):a//2)]
[[6, 3], [4, 10], [9, 1], [2, 5], [7, 0], [8]]
Upvotes: 0
Reputation: 107347
You can use itertools.izip_longest
(itertools.zip_longest
in python 3) :
>>> from itertools import izip_longest
>>> [(a + b) if b else a for a, b in izip_longest(newlis[::2], newlis[1::2])]
[[6, 3], [4, 10], [9, 1], [2, 5], [7, 0], [8]]
This function also accept a fillvalue
that you can use to fill the missed values with a costume value :
>>> [(a + b) for a, b in izip_longest(newlis[::2], newlis[1::2],fillvalue=['**'])]
[[6, 3], [4, 10], [9, 1], [2, 5], [7, 0], [8, '**']]
One another choice is using chain
and islice
:
>>> from itertools import islice,chain
>>> [list(chain.from_iterable(islice(newlis,i,i+2))) for i in range(0,len(newlis),2)]
[[6, 3], [4, 10], [9, 1], [2, 5], [7, 0], [8]]
Upvotes: 1