繁体   English   中英

Python 3 二维列表推导

[英]Python 3 two dimensional list comprehension

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

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]

但这只是用None填充 list_final 。 我看过一些教程,但我似乎无法将我的大脑围绕在这个概念上。 任何帮助,将不胜感激。

您的代码中发生了什么:

list_final = [x if [x,0] in list_two else [None,None] for x in list_one]
  1. list_one并将其所有元素替换为
  2. 要么x (又名保持完整) IF [x,0]存在于list_two但是,见下文)
  3. 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. 但只尝试这样做 IF k in list_two
  3. ELSE 用[None, None]替换此条目。

你可以试试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM