基于特定元素合并值不为null/none的数组

2024-04-29 03:45:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直试图用一个公共字段连接多个数组,但没有成功。我想从这样的情况出发:

mainArray = [['dog', None, None, 'bark', None], 
             ['dog', 'brown', None, None, None],
             ['dog', None, 'happy', None, None],
             ['cat', 'black', None, None, None],
             ['cat', None, None, 'soft', None],
             ['cat', None, None, None, 'purr']]

对这样的事情:

mainArray = [['dog', 'brown', 'happy', 'bark', None],
             ['cat', 'black', None, 'soft', 'purr']]

我知道这应该是相当简单,但我还没有找到一个正确的实现这一点。请把我引向正确的方向。你知道吗


Tags: none情况数组方向事情catsoftblack
2条回答

假设键是每个子列表的第一项,并且不匹配的字段不会重叠,那么使用^{}^{}有一种方法:

from itertools import groupby, dropwhile

r = [[next(dropwhile(lambda x: x is None, i), None) for i in zip(*g)] 
                       for _, g in groupby(mainArray, lambda x: x[0])]
print(r)
# [['dog', 'brown', 'happy', 'bark', None], 
#  ['cat', 'black', None, 'soft', 'purr']]

您可以这样做,假设每个子数组的每个位置都有一个以上的非None值(如示例数据所示):

import collections
from pprint import pprint

mainArray = [['dog', None, None, 'bark', None],
             ['dog', 'brown', None, None, None],
             ['dog', None, 'happy', None, None],
             ['cat', 'black', None, None, None],
             ['cat', None, None, 'soft', None],
             ['cat', None, None, None, 'purr']]

temp_dict = collections.OrderedDict()
for row in mainArray:
    key = row[0]
    if key not in temp_dict:
        temp_dict[key] = [row[1:]]
    else:
        temp_dict[key].append(row[1:])

mainArray = []
for key,rows in temp_dict.items():
    merged = [None] * len(rows[0])
    for row in rows:
        for i in range(len(row)):
            if row[i] is not None:
                merged[i] = row[i]
    mainArray.append([key] + merged)

pprint(mainArray)

输出(这是正确的,尽管与您显示的略有不同):

[['dog', 'brown', 'happy', 'bark', None],
 ['cat', 'black', None, 'soft', 'purr']]

相关问题 更多 >