Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将列表与字典进行比较_Python_List_Dictionary - Fatal编程技术网

Python 将列表与字典进行比较

Python 将列表与字典进行比较,python,list,dictionary,Python,List,Dictionary,我的名单是 candidates= [[714, 1023, 768, 1078], [803, 938, 868, 995]] 我的字典是: main_dict = {(1561, 48, 1623, 105): [[[1592, 58]], [[1591, 59]], [[1585, 59]],

我的名单是

candidates= [[714, 1023, 768, 1078], [803, 938, 868, 995]]
我的字典是:

main_dict = {(1561, 48, 1623, 105): [[[1592, 58]],
                                     [[1591, 59]],
                                     [[1585, 59]],
                                     [[1600, 58]]],

             (714, 1023, 768, 1078): [[[1, 5]],
                                      [[2, 6]],
                                      [[3, 3]],
                                      [[4, 3]]],

             (803, 938, 868, 995): [[[14, 5]],
                                    [[22, 64]],
                                    [[34, 31]],
                                    [[43, 32]]]

             }
我希望有两个列表,
main\u dict\u key
中存在的
候选值,其中包含
主目录中存在的
候选值的相应
值,另一个列表包含
主目录
中的值
,但不在
候选目录

这是我尝试过的,非常混乱和缓慢。有人能有更快的方法吗?此外,如何使else语句具有键列表
v
,这些键列表不存在于
candidate\u values\u存在于\u dict\u key
中,而存在于
main\u dict

可以保证
候选者
值始终位于
主键
中,并且与
候选者
的出现顺序相同

candidate_values_exists_in_dict_key = []

values_of_main_dict_not_in_candidates_values_list=[] 

for x in candidates:
    for k, v in main_dict.items():
        if x == list(k):
            candidate_values_exists_in_dict_key.append(v)

只要一个普通的列表理解和dict查找就可以了。不需要嵌套循环

candidate_values_exists_in_dict_key = [main_dict[tuple(c)] for c in candidates]

values_of_main_dict_not_in_candidates_values_list = [v for k,v in main_dict.items() if list(k) not in candidates]


如果您想输出一个候选值列表之外的一个候选值列表,那么在任何情况下都必须以一种或另一种形式遍历字典

因此,问题中的代码基本上是好的。但您可以通过使用一组候选对象(转换为用作字典键的元组)来测试包含,而不是使用嵌套循环来稍微改进它。因为您知道它们用作字典键,所以您也知道它们可以用作集合的元素

candidate_tuples = set(map(tuple, candidates))

candidate_values_exists_in_dict_key = []
values_of_main_dict_not_in_candidates_values_list = [] 

for k, v in main_dict.items():
    if k in candidate_tuples:
        candidate_values_exists_in_dict_key.append(v)
    else:
        values_of_main_dict_not_in_candidates_values_list.append(v)

如何
values\u of\u main\u dict\u not\u in\u candidates\u values\u list
Updated my answer从字典中创建一个包含所有键的列表。然后是两个不同的条件。首先是
x=list(set(list1).symmetric_-difference(list2))
y=list(set(list2).symmetric_-difference(list1))
,它们将为您提供所需的密钥列表。然后通过主目录进行搜索以获得每组值。这样行吗?