2017-10-20 106 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']]