合并二维阵列

2024-09-30 01:28:08 发布

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

假设我有两个数组:

arrayOne = [["james", 35], ["michael", 28], ["steven", 23], 
            ["jack", 18], ["robert", 12]]
arrayTwo = [["charles", 45], ["james",  36], ["trevor", 24], 
            ["michael", 17], ["steven", 4]]

我想合并它们,这样我就有一个二维数组,其中每个内部数组的第一个元素就是名称(james、charles等)。内部数组的第二个元素是其在arrayOne中的相应值,如果没有相应的值,则为0。第三个元素则相反。只要数字和名字匹配,顺序就不重要了。换句话说,我会得到这样的东西

^{pr2}$

另外,我正在尝试使用它,这样如果我给另一个数组,我可以向这个数组结果添加更多的“列”。在


Tags: 名称元素顺序数字数组名字robertjack
2条回答

看起来你真正需要的是字典,而不是数组。如果你用字典,这个问题就简单多了。转换为dicts非常简单:

dictOne = dict(arrayOne)
dictTwo = dict(arrayTwo)

从那里,你可以把它们组合成这样:

^{pr2}$

它的作用是创建一个名为combined的新字典,我们将把最后的数据放入其中。然后,我们从两个原始字典中生成一组键。使用一套设备确保我们不会重复任何事情。最后,我们循环使用这组键并将每对值添加到combined字典中,告诉调用.get方法以在不存在值的情况下提供0。如果需要将组合字典切换回数组,这也非常简单:

arrayResult = []
for name in combined:
  arrayResult.append([ name ] + combined[name])

假设要将另一列添加到结果字典中,只需将中间代码改为如下所示:

combined = dict()
for name in set(dictOne.keys() + dictTwo.keys() + dictThree.keys()):
  combined[name] = [ dictOne.get(name, 0), dictTwo.get(name, 0), dictThree.get(name, 0) ]

如果您想将所有这些逻辑封装在一个函数中(我建议您这样做),可以这样做:

def combine(*args):
  # Create a list of dictionaries from the arrays we passed in, since we are
  # going to use dictionaries to solve the problem.
  dicts = [ dict(a) for a in args ]

  # Create a list of names by looping through all dictionaries, and through all
  # the names in each dictionary, adding to a master list of names
  names = []
  for d in dicts:
    for name in d.keys():
      names.append(name)

  # Remove duplicates in our list of names by making it a set
  names = set(names)

  # Create a result dict to store results in
  result = dict()

  # Loop through all the names, and add a row for each name, pulling data from
  # each dict we created in the beginning
  for name in names:
    result[name] = [ d.get(name, 0) for d in dicts ]

  # Return, secure in the knowledge of a job well done. :-)
  return result

# Use the function:
resultDict = combine(arrayOne, arrayTwo, arrayThree)
>>> dict1 = dict(arrayOne)
>>> dict2 = dict(arrayTwo)
>>> keyset = set(dict1.keys() + dict2.keys())
>>> [[key, dict1.get(key, 0), dict2.get(key, 0)] for key in keyset]
[['james', 35, 36], ['robert', 12, 0], ['charles', 0, 45], 
 ['michael', 28, 17], ['trevor', 0, 24], ['jack', 18, 0], 
 ['steven', 23, 4]]

如果要添加多个列,这会变得更加复杂;那么最好使用字典。但是将0放在正确的位置是一个挑战,因为当我们向“主字典”添加一个名称时,我们必须确保它以一个长度正确的0列表开头。首先,我想创建一个基于基本类的函数:

^{pr2}$

输出:

{'james': [35, 36], 'robert': [12, 0], 'charles': [0, 45], 
 'michael': [28, 17], 'trevor': [0, 24], 'jack': [18, 0], 
 'steven': [23, 4]}
{'james': [35, 36, 39], 'robert': [12, 0, 0], 'charles': [0, 45, 0], 
  'michael': [28, 17, 13], 'trevor': [0, 24, 0], 'olliver': [0, 0, 11], 
  'jack': [18, 0, 0], 'steven': [23, 4, 6], 'john': [0, 0, 22]}

相关问题 更多 >

    热门问题