不知道如何从函数返回值

时间:2016-06-17 09:01:58

标签: python return

我有一个代码,我需要返回值,但我想我无法正确放置return语句。我需要将组合的IP地址列表返回给python中的调用函数

def call_me ():
  ACCESS_KEY= "XX"
  SECRET_KEY= "XXXX"
  regions = ['us-west-2','eu-central-1','ap-southeast-1']
  for region in regions:
    instance_information = {}
    ip_dict = {}
    client = boto3.client('ec2',aws_access_key_id=ACCESS_KEY,aws_secret_access_key=SECRET_KEY,region_name=region,)
    addresses_dict = client.describe_addresses().get('Addresses')

    for address in addresses_dict:

        if address.get('InstanceId'):
            instance_information[address['InstanceId']] = [address.get('PublicIp')]
         #   print  instance_information

    dex_dict = client.describe_tags().get('Tags')
    for dex in dex_dict:
        if instance_information.get(dex['ResourceId']):
            instance_information[dex['ResourceId']].append(dex.get('Value'))
    for instance in instance_information:

        if len(instance_information[instance]) == 2:
            ip_dict[instance_information[instance][0]] = instance_information[instance][1]
        else:
            ip_dict[instance_information[instance][0]] = ''
#    print (json.dumps(instance_information,indent=4))
    #print type(instance_information)
    ip_list = [i[0]  for i in instance_information.values()]
    print (ip_list)

现在我不确定将return ip_list语句放在何处,因为它在3个区域中运行

2 个答案:

答案 0 :(得分:0)

您可以在ip_list循环之前定义for,并使用每个地区的值列表extend定义:{/ p>

ip_list = []
for region in regions:
    instance_information = {}
    #
    # your code
    #
    ip_list.extend(i[0]  for i in instance_information.values())
    print(ip_list)
return ip_list

如果要保留列表列表中区域的值,则可以将扩展行替换为:ip_list.append([i[0] for i in instance_information.values()])

答案 1 :(得分:0)

您的问题不在于何处放置return语句。问题是您在ip_list循环的每次迭代中重新定义for,因此您无法获得所有信息以返回它。

我不确定您想要返回值的确切格式,但也许您可以在for循环之前将combined_ip_list变量定义为空列表,并附加值{{1}而不是在该循环结束时打印它,然后在循环外返回该值。