Python 3二维列表理解

时间:2017-10-20 01:34:08

标签: python python-3.x list list-comprehension

我有两个用于组装第三个的列表。我将list_one与list_two进行比较,如果list_one中的字段值位于list_two中,则list_two中的值都将复制到list_final中。如果list_two中缺少字段的值,那么我希望看到一个空值(None)放入list_final。 list_final将具有与list_one相同的项目数和顺序:

psutil

list_final的值应为:

list_one = ['one', 'two', 'three', 'four', 'five', 'six', 'seven']
list_two = [['seven','7'], ['five','5'], ['four','4'], ['three','3'], ['one','1']]
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。我看了一些教程,但我似乎无法围绕这个概念包围我的脑子。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

您的代码中发生了什么:

list_final = [x if [x,0] in list_two else [None,None] for x in list_one]
  1. list_one并用
  2. 替换所有元素
  3. x(又名保持原样)[x,0]中存在list_two,见下文)
  4. ELSE用[None, None]替换当前元素。
  5. 由于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 :(得分: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']]