我有2个名单:
correct_list = [1,2,3,4,5,6,7,8,9,10]
other_list = [4,5,6,7,8,10]
我想将这两个列表结合起来:
combined_list = [{k:1, v:0},{k:2, v:0},{k:3, v:0}, {k:4, v:4}, {etc}]
所以基本上我说的是密钥是正确的列表,而且where_list与correct_list不匹配,请填写0或“”。并且它们匹配,填写匹配值
这有意义吗?
我将如何在python中执行此操作?
答案 0 :(得分:4)
[{'k': c, 'v': c if c in other_list else 0} for c in correct_list]
顺便说一句,如果字典中唯一的元素是k和v,请考虑构建字典而不是字典列表:
>>> dict((c, c if c in other_list else 0) for c in correct_list)
{1: 0, 2: 0, 3: 0, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 0, 10: 10}