假设我有两个数组:
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。第三个元素则相反。只要数字和名字匹配,顺序就不重要了。换句话说,我会得到这样的东西
另外,我正在尝试使用它,这样如果我给另一个数组,我可以向这个数组结果添加更多的“列”。在
看起来你真正需要的是字典,而不是数组。如果你用字典,这个问题就简单多了。转换为dicts非常简单:
从那里,你可以把它们组合成这样:
^{pr2}$它的作用是创建一个名为
combined
的新字典,我们将把最后的数据放入其中。然后,我们从两个原始字典中生成一组键。使用一套设备确保我们不会重复任何事情。最后,我们循环使用这组键并将每对值添加到combined
字典中,告诉调用.get
方法以在不存在值的情况下提供0
。如果需要将组合字典切换回数组,这也非常简单:假设要将另一列添加到结果字典中,只需将中间代码改为如下所示:
如果您想将所有这些逻辑封装在一个函数中(我建议您这样做),可以这样做:
如果要添加多个列,这会变得更加复杂;那么最好使用字典。但是将
^{pr2}$0
放在正确的位置是一个挑战,因为当我们向“主字典”添加一个名称时,我们必须确保它以一个长度正确的0
列表开头。首先,我想创建一个基于基本类的函数:输出:
相关问题 更多 >
编程相关推荐