我在这样的列表中有一个字典:
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]
带有(键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]]
如何实现我的输出?任何想法都很棒。
这可以通过将lists
转换为sets
来实现,以便分别对non_matching_list
和matching_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()
函数来聚合每个可迭代项(两个列表(中的元素。