2017-10-20 129 views
2

我有兩個列表,用於組裝第三個列表。我將list_one與list_two進行了比較,如果list_one中的某個字段的值位於list_two中,則兩個來自list_two的值都將被複制到list_final中。如果一個字段的值從list_two中丟失,那麼我希望看到一個空值(無)放入list_final中。 list_final將有相同數量的項目,並在相同的順序list_one:Python 3二維列表理解

list_one = ['one', 'two', 'three', 'four', 'five', 'six', 'seven'] 
list_two = [['seven','7'], ['five','5'], ['four','4'], ['three','3'], ['one','1']] 
list_final = [] 

list_final的值應爲:

[['one','1'], [None,None], ['three','3'], ['four','4'], ['five','5'], [None,None], ['seven','7']] 

我已經得到最接近的是:

list_final = [x if [x,0] in list_two else [None,None] for x in list_one] 

但這只是填充list_final None。我已經看了一些教程,但我似乎無法圍繞這個概念包圍我的大腦。任何幫助,將不勝感激。

+4

'list_two'應該更好地(或轉換成)一個字典,然後你做像'dict_two.get('七')''獲得''7'這使得列表理解更容易 –

回答

2

發生了什麼事在你的代碼:

list_final = [x if [x,0] in list_two else [None,None] for x in list_one] 
  1. list_one
  2. 取代所有的元素
  3. 要麼x(又名保持完好)是否存在於list_two[x,0],見下文)
  4. ELSE與[None, None]替換當前的元素。

而作爲list_two不包含匹配[x,0]任何元素(無論是你定的例子x),所有的值被替換[None, None]

工作液

list_one = ['one', 'two', 'three', 'four', 'five', 'six', 'seven'] 
list_two = [['seven','7'], ['five','5'], ['four','4'], ['three','3'], ['one','1']] 

# Turns list_two into a nice and convenient dict much easier to work with 
# (Could be inline, but best do it once and for all) 
list_two = dict(list_two) # {'one': '1', 'three': '3', etc} 

list_final = [[k, list_two[k]] if k in list_two else [None, None] for k in list_one] 

礦,在另一方面:

  1. 獲取你你想要什麼,又名[k, dict(list_two)[k]]
  2. 但只嘗試這樣做,如果k in list_two
  3. ELSE用[None, None]替換此條目。
+1

感謝答案和**超謝謝你**的解釋! – Jarvis

+0

@Jarvis希望它可以幫助...這就是我寫的。隨意問任何問題(只要你告訴我們你到目前爲止已經嘗試了什麼,等等...通常:)) – JeromeJ

0

你可以試試這個:

list_one = ['one', 'two', 'three', 'four', 'five', 'six', 'seven'] 
list_two = [['seven','7'], ['five','5'], ['four','4'], ['three','3'], ['one','1']] 
final_list = [[None, None] if not any(i in b for b in list_two) else [c for c in list_two if i in c][0] for i in list_one] 
print(final_list) 

輸出:

[['one', '1'], [None, None], ['three', '3'], ['four', '4'], ['five', '5'], [None, None], ['seven', '7']]