假设我有两个数组:
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。第三个元素则相反。只要数字与名称匹配,顺序并不重要。换句话说,我会得到这样的东西
arrayResult = [["james", 35, 36], ["michael", 28, 17], ["steven", 23, 4],
["jack", 18, 0], ["robert", 12, 0], ["charles", 0, 45],
["trevor", 0, 4]]
此外,我正在尝试拥有它,以便在我要提供另一个数组时可以向该数组结果添加更多“列”。
最佳答案
看起来您真正需要的是字典,而不是数组。如果你使用字典,这个问题就会变得容易得多。转换为字典再简单不过了:
dictOne = dict(arrayOne)
dictTwo = dict(arrayTwo)
从那里,你可以像这样把它们放在一起:
combined = dict()
for name in set(dictOne.keys() + dictTwo.keys()):
combined[name] = [ dictOne.get(name, 0), dictTwo.get(name, 0) ]
这样做是创建一个名为 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)
关于python - 合并二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5062323/