合并列表列表,例如
list_of_lists = [['NA','NA','NA','0,678'], ['0.327','NA','NA','NA'], ...]
我想要
merged = ['0.327','NA','NA','0,678']
请评论。
答案 0 :(得分:2)
使用带有嵌套生成器表达式的列表推导来选择第一个非NA
元素以及zip()
:
merged = [next((el for el in elements if el != 'NA'), 'NA') for elements in zip(*list_of_lists)]
演示:
>>> 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']
next((...), default)
调用表达式将选择不等于'NA'
的第一个元素,如果不存在此类元素,则返回'NA'
。
答案 1 :(得分:0)
假设两个列表都没有相同位置的值(如Martijn Pieters所建议的那样),那么您可以使用:
for i in range(len(l1)):
l1[i] = l2[i] if l1[i] == 'NA' and l2[i] != 'NA' else l1[i]
希望这有帮助!
答案 2 :(得分:0)
>>> 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']