Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python List, 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading