Dawit Eshetu
Dawit Eshetu

Reputation: 49

Changing 2D element of a list to 1D element

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']]

Upvotes: 0

Views: 52

Answers (1)

user7864386
user7864386

Reputation:

New answer (edited in after OP's edit):

Given

c = [ [[x] * y for x, y in zip(a, row)] for row in b ]

You can simply iterate over the new sublist as you create it:

c = [ [i for x, y in zip(a, row) for i in [x]*y] for row in b]

or use itertools.chain if that's what you prefer:

c = [ list(chain.from_iterable([x]*y for x, y in zip(a, row))) for row in b]

Output:

[['one', 'two', 'two'], ['one', 'one', 'one', 'two', 'two', 'two']]

Old answer:

Given

lst = [['one'], ['two', 'two'], ['one', 'one', 'one'], ['two', 'two', 'two']]

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']]

Upvotes: 3

Related Questions