Concatenate pairs of consecutive sublists in a list using Python -
how combine sublists within list pairs? example with:
list1 = [[1,2,3],[4,5],[6],[7,8],[9,10]]
the result be:
[[1,2,3,4,5],[6,7,8],[9,10]]
you use zip_longest
fill value (in case list has odd number of sublists) zip iterator on list1
. running list comprehension on zip generator object allows concatenate consecutive pairs of lists:
>>> itertools import zip_longest # izip_longest in python 2.x >>> x = iter(list1) >>> [a+b a, b in zip_longest(x, x, fillvalue=[])] [[1, 2, 3, 4, 5], [6, 7, 8], [9, 10]]
Comments
Post a Comment