I wanted to change 2D element of a list to 1D in the following code.
from itertools import chain
a = ['one', 'two']
b = [[1, 2], [3, 3]]
c = [ [[x] * y for x, y in zip(a, row)] for row in b ]
c = list(chain.from_iterable(c))
print(c)
The out put was
[['one'], ['two', 'two'], ['one', 'one', 'one'], ['two', 'two', 'two']]
if
c = [ [x * y for x, y in zip(a, row)] for row in b ]
the result would be
[['Amh', 'EngEng'], ['AmhAmhAmh', 'EngEngEng']]
But I wanted the result to be as the following using list comprehension.
[['one', 'two', 'two'], ['one', 'one', 'one', 'two', 'two', 'two']]
>Solution :
New:
You can simply iterate over the new sublist to unpack:
c = [ [i for x, y in zip(a, row) for i in [x]*y] for row in b]
Output:
[['one', 'two', 'two'], ['one', 'one', 'one', 'two', 'two', 'two']]
Old answer:
You could concatenate lists in a list comprehension using range:
out = [lst[i] + lst[i+1] for i in range(0, len(lst), 2)]
or using zip:
out = [li1+li2 for li1, li2 in zip(lst[::2], lst[1::2])]
Output:
[['one', 'two', 'two'], ['one', 'one', 'one', 'two', 'two', 'two']]