我在这样的列表中有一个字典:
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], []]}]
现在,我想用键1
的第一个值检查列表中键2
的第一个值。
像这样的东西
比较值(键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]]
如何实现输出?任何想法都很棒。
答案 0 :(得分:1)
这可以通过将lists
和sets
分别转换为symmetric_difference()
和intersection()
来进行,例如将non_matching_list
转换为matching_list
。
这是解决方案之一:
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()
函数聚合每个可迭代对象(两个列表)中的元素。