简体   繁体   English

遍历字典中的列表并与列表中的列表进行比较

[英]Looping through lists in a dictionary and comparing to lists in a list

I am quite new to python so bear with me. 我是python的新手,所以请多多包涵。

Basically I have two sets of a data. 基本上我有两组数据。 One is a dictionary that is made up of lists and the other is a list made up of lists: 一个是由列表组成的字典,另一个是由列表组成的列表:

my_dict =  {1: [1], 2: [1, 2], 3: [1, 3], 4: [1, 3, 4], 5: [1, 3, 4, 5], 6: [1, 3, 4, 5, 6]}

my_list = ([1, 1, 0], [1, 2, 100], [1, 3, 150], [1, 4, 150], [1, 5, 10], [1, 6, 20])

I want to compare the first two numbers in the list, with the numbers in the lists in the dictionary. 我想将列表中的前两个数字与字典中列表中的数字进行比较。 When the first two numbers in the list (ie (1,2)) are found in the lists in the dictionary I append the THIRD item in the list of lists to a new list (ie (100)). 当在字典的列表中找到列表中的前两个数字(即(1,2))时,我将列表列表中的THIRD项目附加到新列表(即(100))上。

Here is my code so far: 到目前为止,这是我的代码:

def AON(my_dict, my_list):
    new_list = []
    o_d = 0

for key in my_dict:

    if my_list[o_d][0] and my_list[o_d][1] in my_dict[key]:
        new_list.append(my_list[o_d][2])
        o_d += 1
    else:
        o_d += 1

print (o_d)
print(new_list)

return new_list
return o_d
AON(my_dict, my_list)

The output is as follows: 输出如下:

new_list = [0, 100, 150, 150, 10, 20]

My problem is that my list of lists has 600 lists with three items each in them. 我的问题是我的列表列表有600个列表,每个列表中有三个项目。 My dictionary of lists has only 25 keys. 我的列表字典只有25个键。 My result is that new_list has only 25 items in it - where in actual fact there should be 600 (as items such as (1,3) are found throughout the list of lists. How do I make my loop keep checking for similar items between my_dict and my_list 600 times rather than just 25 times? 我的结果是new_list中只有25个项目-实际上应该有600个项目(因为在整个列表列表中都可以找到(1,3)之类的项目。如何使我的循环不断检查之间的相似项目my_dict和my_list 600次而不是25次?

Thanks! 谢谢!

You are looping over my_dict , and adding (at most) one item per key value into new_list . 您正在遍历my_dict ,并将每个键值(最多)添加一项到new_list

Instead, loop over my_list , and look for the first two elements of each in the dictionary to see if the associated value should be added to new_list . 相反,请遍历my_list ,并在字典中查找每个元素的前两个元素,以查看是否应将关联的值添加到new_list

This should give the desired result. 这应该给出期望的结果。

Create a set of all numbers in the dictionary values first: 首先在字典值中创建一组所有数字:

numbers = set()
for v in my_dict.values():
    numbers.update(set(v))

Now, take all third entries if the first two are in the numbers: 现在,如果前两个数字都在数字中,则输入所有第三项:

res = [v3 for v1, v2, v3 in my_list if v1 in numbers and v2 in numbers]

print(res)

Result: 结果:

[0, 100, 150, 150, 10, 20]

Instead of looping over my_dict , just loop over my_list . 除了循环my_dict ,还可以循环my_list

You can condense your loop to a single list comprehension: 您可以将循环压缩为单个列表理解:

[x3 for x1,x2,x3 in my_list if x1 in my_dict and x2 in my_dict]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM