Process1
Process1

Reputation: 488

how to merge list of lists without changing the order of sublists in python?

merge list of lists for example

list_of_lists = [['NA','NA','NA','0,678'], ['0.327','NA','NA','NA'], ...]

I want

merged = ['0.327','NA','NA','0,678']

Please comment.

Upvotes: 0

Views: 172

Answers (3)

jamylak
jamylak

Reputation: 133554

>>> list_of_lists = [['NA','NA','NA','0,678'], ['0.327','NA','NA','NA']]
>>> from itertools import ifilter # Py3k doesn't need import, use filter built-in
>>> [next(ifilter('NA'.__ne__, col), 'NA') for col in zip(*list_of_lists)]
['0.327', 'NA', 'NA', '0,678']

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121914

Use a list comprehension with a nested generator expression to pick the first non-NA element, together with zip():

merged = [next((el for el in elements if el != 'NA'), 'NA') for elements in zip(*list_of_lists)]

Demo:

>>> list_of_lists = [['NA','NA','NA','0,678'], ['0.327','NA','NA','NA']]
>>> [next((el for el in elements if el != 'NA'), 'NA') for elements in zip(*list_of_lists)]
['0.327', 'NA', 'NA', '0,678']

The next((...), default) call expression will pick the first element that is not equal to 'NA', falling back to 'NA' if no such element exists.

Upvotes: 2

Nick Burns
Nick Burns

Reputation: 983

Assuming that there both list do not have values in the same position (as suggested by Martijn Pieters) then you could use:

for i in range(len(l1)): 
    l1[i] = l2[i] if l1[i] == 'NA' and l2[i] != 'NA' else l1[i]

Hope this helps!

Upvotes: 0

Related Questions