Python的if语句产生了误报的结果

huangapple go评论62阅读模式
英文:

Python if creates false positive result

问题

以下是您提供的代码的翻译部分:

我正在尝试通过列出所有资源并检查它们是否具有特殊的 `troux` 标签来调查我的AWS资源

当迭代我的结果时对于某些资源我得到了重复的行同时声明 `troux` 标签存在和不存在

import boto3
import ssl

ssl._create_default_https_context = ssl._create_unverified_context

# 如果使用WSL2
boto3.setup_default_session(profile_name='profile')

client = boto3.client('cloudformation')
paginator = client.get_paginator('describe_stacks')
page_iterator = paginator.paginate()

result = []

for page in page_iterator:
    for stack in page['Stacks']:
        if "department_name_" in stack["StackName"]:
            for dict in stack["Tags"]:
                for key, value in dict.items():
                    if value in ("troux_id", "troux_uid"):
                        stack_with_troux = stack["StackName"] + " " + dict.get('Key') + ": " + dict.get('Value')
                        result.append(stack_with_troux)
                    else:
                        stack_without_troux = stack["StackName"] + " is missing troux tag!"
                        result.append(stack_without_troux)

print(result)

for dict in stack["Tags"]: 返回以下数据:

{ 'Key': 'tag', 'Value': 'abc' }
{ 'Key': 'tag', 'Value': 'abc' }
{ 'Key': 'tag', 'Value': 'abc' }
{ 'Key': 'troux_id', 'Value': 'xyz' }
{ 'Key': 'tag', 'Value': 'xyz' }
{ 'Key': 'tag', 'Value': 'abc' }
{ 'Key'......

最终结果是:

department_name_resource_one 缺少 troux 标签!
department_name_resource_one 缺少 troux 标签!
department_name_resource_one 缺少 troux 标签!
department_name_resource_one 缺少 troux 标签!
department_name_resource_one troux_id: xyz
department_name_resource_one 缺少 troux 标签!

预期的是,如果找到 troux,则循环应该停止,否则打印 缺少标签

department_name_resource_one 缺少 troux 标签!
department_name_resource_two troux_id: xyz
department_name_resource_three 缺少 troux 标签!

英文:

I'm trying to investigate my AWS resources by listing all and checking whether they have special troux tag.

When iterating through my results I'm getting duplicate rows for some resources, both stating that troux tag does and doesn't exist at the same time.

import boto3
import ssl

ssl._create_default_https_context = ssl._create_unverified_context

#if using WSL2
boto3.setup_default_session(profile_name='profile')

client = boto3.client('cloudformation')
paginator = client.get_paginator('describe_stacks')
page_iterator = paginator.paginate()

result = []

for page in page_iterator:
    for stack in page['Stacks']:
        if "department_name_" in stack["StackName"]:
            for dict in stack["Tags"]:
                for key, value in dict.items():
                    if value in ("troux_id", "troux_uid"):
                        stack_with_troux = stack["StackName"] + " " + dict.get('Key') + ": " + dict.get('Value')
                        result.append(stack_with_troux)
                    else:
                        stack_without_troux = stack["StackName"] + " is missing troux tag!"
                        result.append(stack_without_troux)


print(result)

for dict in stack["Tags"]: returns following data:

{'Key': 'tag', 'Value': 'abc'}
{'Key': 'tag', 'Value': 'abc'}
{'Key': 'tag', 'Value': 'abc'}
{'Key': 'troux_id', 'Value': 'xyz'}
{'Key': 'tag', 'Value': 'xyz'}
{'Key': 'tag', 'Value': 'abc'}
{'Key'......

Final outcome is:

department_name_resource_one  is missing troux tag!
department_name_resource_one  is missing troux tag!
department_name_resource_one  is missing troux tag!
department_name_resource_one  is missing troux tag!
department_name_resource_one  troux_id: xyz
department_name_resource_one  is missing troux tag!

Expected is that loop should stop if troux is found else print missing tag

department_name_resource_one  is missing troux tag!
department_name_resource_two  troux_id: xyz
department_name_resource_three is missing troux tag!

答案1

得分: 2

Here is the translation of the code-related content:

for key, value in dict.items():
每个字典都有两个条目。因此,对于每个字典,循环将执行两次。
For this dictionary {'Key': 'troux_id', 'Value': 'xyz'}, the if statement
对于这个字典 {'Key': 'troux_id', 'Value': 'xyz'},如果语句
if value in ("troux_id", "troux_uid"):
如果值等于 "troux_id" 或 "troux_uid" 中的一个:
... is true for one of those loop iterations (where the value is troux_id), and false for the other (where the value is xyz).
...在其中一个循环迭代中为真(其中值为 troux_id),在另一个循环迭代中为假(其中值为 xyz)。
The real problem is that you're printing "missing tag" if the current item doesn't match, when instead you should wait until you've seen all of the items in a dict, and only print that message if none of them matched.
真正的问题是,如果当前项不匹配,你会打印 "missing tag",而你应该等到看到字典中的所有项后,只有在没有匹配项时才打印该消息。

Please note that I've only translated the code-related content as per your request. If you have any specific questions or need further assistance, feel free to ask.

英文:
for key, value in dict.items():

Each of those dicts has two items. Therefore the loop will execute twice for each dict.

For this dictionary {'Key': 'troux_id', 'Value': 'xyz'}, the if statement

if value in ("troux_id", "troux_uid"):

... is true for one of those loop iterations (where the value is troux_id), and false for the other (where the value is xyz).

The real problem is that you're printing "missing tag" if the current item doesn't match, when instead you should wait until you've seen all of the items in a dict, and only print that message if none of them matched.

huangapple
  • 本文由 发表于 2023年5月30日 05:21:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76360381.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定