简体   繁体   English

是否可以在python的列表理解中使用多个条件?

[英]Is possible to use multiple conditions in list comprehension in python?

trying to get a list of instances on AWS EC2 with tag 'Name' of an instance contain certain value.尝试获取 AWS EC2 上的实例列表,其中实例的标签“名称”包含特定值。

This snippet is functional, but think we can make it cleaner :这段代码很实用,但认为我们可以让它更干净:

# -*- coding: utf-8 -*-

import sys
import boto3

class proxies_on_ec2():
   def __init__(self, **kwargs):
      self.ec2client = boto3.resource('ec2')

   def get_list(self):
      self.get_all_instances = self.ec2client.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
    
      self.instances_list = []

      for instance in self.get_all_instances:
         for tag in instance.tags:
            if tag.get('Key') == 'Name':
               if "[Dev]" in tag['Value']:
                    self.instances_list.append({'Name': tag['Value'], 'id': instance.id, 'ip': instance.public_ip_address})

    return self.instances_list

I can't get the similar result with list comprehension :我无法通过列表理解获得类似的结果:

self.instances_list = [{'Name':instance.tags[0].get('Value'), 'id':instance.id, 'ip':instance.public_ip_address} for instance in self.get_all_instances]

problem is instance.tags[0].问题是 instance.tags[0]。 Is it possible to add 'if tag.get('Key') == 'Name' and replace instance.tags[0] to instance.tag after this condition ?是否可以在此条件之后添加 'if tag.get('Key') == 'Name' 并将 instance.tags[0] 替换为 instance.tag ?

Thanks for help感谢帮助

self.instances_list = [
    {"Name": tag["Value"], "id": instance.id, "ip": instance.public_ip_address}
    for instance in self.get_all_instances
    for tag in instance.tags
    if tag.get("Key") == "Name" and "[Dev]" in tag["Value"]
]

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

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