简体   繁体   English

如何解决此循环以打印所有值?

[英]How to solve this loop to print all the values?

It should print 5,3.33 but it is only printing 3?How to print both values它应该打印 5,3.33 但它只打印 3?如何打印这两个值

bucket_data22={1: {'key': 'Security Awareness Overview', 'value': 20, 'start_date': '13/07/2021', 'end_date': '12/08/2021', 'id': 155}, 
             2: {'key': 'Security Awareness Overview', 'value': 0, 'start_date': '13/07/2021', 'end_date': '12/08/2021', 'id': 159}, 
             3:  {'key': 'Security Awareness Overview', 'value': 30, 'start_date': '24/09/2021', 'end_date': '27/09/2021', 'id': 174}}
completed_data={155: 1, 174: 1}
for z in completed_data:
    print(z)
for i in bucket_data22:
    if (bucket_data22[i]['id']==z):
        print((completed_data[z]/bucket_data22[i]['value'])*100)


It works now:它现在有效:

 bucket_data22={1: {'key': 'Security Awareness Overview', 'value': 20, 'start_date': '13/07/2021', 'end_date': '12/08/2021', 'id': 155}, 
                 2: {'key': 'Security Awareness Overview', 'value': 0, 'start_date': '13/07/2021', 'end_date': '12/08/2021', 'id': 159}, 
                 3:  {'key': 'Security Awareness Overview', 'value': 30, 'start_date': '24/09/2021', 'end_date': '27/09/2021', 'id': 174}}

completed_data={155: 1, 174: 1}

for z in completed_data:
    for i in bucket_data22:
        if (bucket_data22[i]['id']==z):
            print((completed_data[z]/bucket_data22[i]['value'])*100)

z has the last value of completed_data, thus you only get one match (the id 174). z具有 completed_data 的最后一个值,因此您只能得到一个匹配项(id 174)。

You should test bucket_data22[i]['id'] in completed_data您应该bucket_data22[i]['id'] in completed_data

for i in bucket_data22:
    if (bucket_data22[i]['id'] in completed_data):
        print((completed_data[z]/bucket_data22[i]['value'])*100)

Output: Output:

5.0
3.3333333333333335

It appears that the second loop only begins after the first one is already finished.似乎第二个循环仅在第一个循环完成后才开始。
Therefore, the second loop always gets the same value of 'z', which equals 174.因此,第二个循环始终获得相同的“z”值,即 174。
If you want to iterate all the values of 'z', you must move the second loop into the first loop.如果要迭代 'z' 的所有值,则必须将第二个循环移到第一个循环中。

bucket_data22={1: {'key': 'Security Awareness Overview', 'value': 20, 'start_date': '13/07/2021', 'end_date': '12/08/2021', 'id': 155}, 
         2: {'key': 'Security Awareness Overview', 'value': 0, 'start_date': '13/07/2021', 'end_date': '12/08/2021', 'id': 159}, 
         3:  {'key': 'Security Awareness Overview', 'value': 30, 'start_date': '24/09/2021', 'end_date': '27/09/2021', 'id': 174}}
completed_data={155: 1, 174: 1}

for z in completed_data:
    for i in bucket_data22:
        if (bucket_data22[i]['id']==z):
          print((completed_data[z]/bucket_data22[i]['value'])*100)

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

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