我有两个列表用于组装第三个。我将 list_one 与 list_two 进行比较,如果 list_one 中某个字段的值位于 list_two 中,则 list_two 中的两个值都将复制到 list_final 中。如果 list_two 中缺少某个字段的值,那么我希望看到将空值 (None) 放入 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]
- 获取
list_one并将其所有元素替换为 - 或者
x(也就是保持原样)如果[x,0]存在于list_two中(但是 ,见下文) - 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]
另一方面,我的:
- 得到你想要的东西,也就是
[k, dict(list_two)[k]] - 但只有当
k in list_two时才尝试这样做 - ELSE 将此条目替换为
[None, None]。
