Reputation: 488
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
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
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
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