簡體   English   中英

合並2d數組

[英]Merging 2d arrays

假設我有兩個數組:

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

我想合並它們,以便我有一個2D數組,其中每個內部數組的第一個元素是名稱(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]]

此外,我試圖讓它,以便我可以添加更多的“列”到這個數組結果,如果我要給另一個數組。

>>> 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列表開頭。 我很想為此創建一個新類,但首先,這是一個基於函數的基本解決方案:

def add_column(masterdict, arr):
    mdlen = len(masterdict[masterdict.keys()[0]])
    newdict = dict(arr)
    keyset = set(masterdict.keys() + newdict.keys())
    for key in keyset:
        if key not in masterdict:
            masterdict[key] = [0] * mdlen
        masterdict[key].append(newdict.get(key, 0))

arrayOne =   [["james", 35],
              ["michael", 28],
              ["steven", 23],
              ["jack", 18],
              ["robert", 12]]
arrayTwo =   [["charles", 45],
              ["james",  36],
              ["trevor", 24],
              ["michael", 17],
              ["steven", 4]]
arrayThree = [["olliver", 11],
              ["james",  39],
              ["john", 22],
              ["michael", 13],
              ["steven", 6]]

masterdict = dict([(i[0], [i[1]]) for i in arrayOne])

add_column(masterdict, arrayTwo)
print masterdict
add_column(masterdict, arrayThree)
print masterdict

輸出:

{'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]}

看起來你真正需要的是字典,而不是數組。 如果使用字典,這個問題就變得容易多了。 轉換為dicts並非易事:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM