例如合并列表列表
list_of_lists = [['NA','NA','NA','0,678'], ['0.327','NA','NA','NA'], ...]
我想
merged = ['0.327','NA','NA','0,678']
请评论。
使用带有嵌套生成器表达式的列表推导来选择第一个非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'
>>> 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']
假设两个列表在同一位置没有值(如 Martijn Pieters 所建议),那么您可以使用:
for i in range(len(l1)):
l1[i] = l2[i] if l1[i] == 'NA' and l2[i] != 'NA' else l1[i]
希望这可以帮助!