简体   繁体   English

如何使用字典理解编写以下代码

[英]How do I write below code using dictionary comprehension

Need help to optimize below python code using dictionary comprehension.需要帮助使用字典理解优化以下 python 代码。 How can modify my code in such a way that using python special features如何以使用 python 特殊功能的方式修改我的代码

        container_status = {}
        active=[]
        inactive=[]
        not_found=[]
        if containers:
            for container in containers:
                inspect_dict = cli.inspect_container(container)
                state = inspect_dict['State']
                is_running = state['Status'] == 'running'
                if is_running:
                    active.append(container)
                else:
                    inactive.append(container)        
            container_status= {'active':active,'inactive':inactive,'not_found':not_found }     
            print(container_status)```

You can try this你可以试试这个

container_status = {}
active=[]
inactive=[]
not_found=[]
inspect_dict = cli.inspect_container('festive_bell')
if containers:              
    ls_to_append = active if inspect_dict['State']['Status'] == 'running' else inactive
    for container in containers:
        ls_to_append.append(container)
    container_status= {'active':active,'inactive':inactive,'not_found':not_found }     
    print(container_status)

Note that each time that it's run it will show all the containers as active or inactive since it's depends on cli.inspect_container('festive_bell') results all of them have the same results请注意,每次运行时,它都会将所有容器显示为活动或非活动,因为它取决于cli.inspect_container('festive_bell')结果,它们都具有相同的结果

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

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