比较属于不同键的字典值

2024-04-25 22:50:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我的字典里有这样一个列表:

sample_dict = [{1: [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], \
                    [1, 2, 3, 4, 5], \
                    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]]}, \
               {2: [[3, 4, 6, 7, 8, 9, 10, 11], [1, 2, 3, 6, 10], []]}]

现在,我想用键2的第一个值检查列表中键1的第一个值。 像这样的事

比较值(键1列表的第一个值)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

with(键2列表的第一个值)

[3, 4, 6, 7, 8, 9, 10, 11]

如果它们是匹配的,我想把它附加到一个新的列表matching_list,如果不是,我想把不匹配的值附加到另一个列表non_matching_list。你知道吗

我已经试过了

matching_list = []
non_matching_list = []

for each_dict in sample_dict:
    current_dict_values = []
    for key, value_list in each_dict.items():
        temp_dict_values = []

        for value in value_list:
            temp_dict_values.append(value)

            .... don't know how to keep track of key 1's first list of lists values.

我想创建一个临时列表来跟踪键1列表值,但是我被卡住了,不知道如何继续。你知道吗

我的最终输出应该是这样的:

matching_list = [[3,4,6,7,8,9,10], [1,2,3], []]
non_matching_list = [[1,2,5,11],[4,5,6,10],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]]

如何实现我的输出?任何想法都会很好。你知道吗


Tags: ofsamplekeyin列表for字典value
1条回答
网友
1楼 · 发布于 2024-04-25 22:50:43

这可以通过将lists转换为sets来实现,从而分别为non_matching_listmatching_list执行symmetric_difference()intersection()等操作。你知道吗

以下是解决方案之一:

matching_list, non_matching_list = [], []

for lists1, lists2 in zip(sample_dict[0].values(), sample_dict[1].values()):
    for l1, l2 in zip(lists1, lists2):
        matching_list.append(list(set(l1) & set(l2)))
        non_matching_list.append(list(set(l1).symmetric_difference(set(l2))))

注意,使用set(l1) & set(l2)set(l1).intersection(set(l2))相同,所以这里基本上是一个交集操作。你知道吗

我还使用内置的zip()函数来聚合每个iterables(两个列表)中的元素。你知道吗

相关问题 更多 >