0

例如合并列表列表

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

我想

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

请评论。

4

3 回答 3

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'

于 2013-04-24T21:24:07.960 回答
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']
于 2013-04-25T06:00:28.383 回答
0

假设两个列表在同一位置没有值(如 Martijn Pieters 所建议),那么您可以使用:

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

希望这可以帮助!

于 2013-04-24T21:30:30.550 回答