2016-11-06 64 views
0

我使用下面的代碼:鞏固與名單列表辭典蟒蛇

dictio = {"Jesse": 6, "Maybel": 3, "Callie": 2, "Maggie": 5} 
cargo = [[6, 3], [5, 2]] 
def transport(dictio, cargo):  
    final = [ ]  
    for i in cargo:  
     for k,v in dictio.items(): 
      for x in i: 
       if x==v: 
        final.append(k) 
       print(final) 
transport(dictio, cargo) 

我的函數打印所有的名字在一個單一的列表:

['Maybel', 'Jesse', 'Maggie', 'Callie'] 

但是,這並不如預期。我應該如何保持原始列表格式的名稱?

[['Maybel', 'Jesse'], ['Maggie', 'Callie']] 
+0

你確定' 'Jesse''沒有(也不應該)之前'出現' Maybel'' ??? (因爲'6'出現在'3'之前)。 –

+0

嗨,順序並不重要 –

回答

3

通過建立相應的子列表:

dictio = {"Jesse": 6, "Maybel": 3, "Callie": 2, "Maggie": 5} 
cargo = [[6, 3], [5, 2]] 

final = [] 
for i in cargo: 
    sub = [] 
    final.append(sub) 
    for k, v in dictio.items(): 
     for x in i: 
      if x == v: 
       sub.append(k) 
print(final) 

輸出:

[['Jesse', 'Maybel'], ['Maggie', 'Callie']] 
+0

工作很好,謝謝! –