列表理解以动态填充对象的属性

List comprehension to dynamically populate attribute of object

动态填充给定属性值列表的正确方法是什么?目前它固定为 3 (0-2),但如果它基于 INSTANCE_PARAMS[i]["instances"].

会更有用

我一直在考虑列表理解,但不确定如何将其写入代码。

for i in INSTANCE_PARAMS:
output = template.add_output([
    Output(
        str(INSTANCE_PARAMS[i]["name"]).capitalize() + "Ips",
        Description="IPs for " + str(INSTANCE_PARAMS[i]["name"]),
        Value=Join(",", [
            GetAtt(ec2.Instance(INSTANCE_PARAMS[i]["name"] + "0"), "PrivateIp"), 
            GetAtt(ec2.Instance(INSTANCE_PARAMS[i]["name"] + "1"), "PrivateIp"), 
            GetAtt(ec2.Instance(INSTANCE_PARAMS[i]["name"] + "2"), "PrivateIp"), 
        ],
        ),
    )
],
)


INSTANCE_PARAMS = {
    "masters": {
        "name": "master",
        "instances": 3,
        "image_id": "ami-xxxxxxxxxx",
        "instance_type": "t1.micro",
        "security_group_id": [
                              "MasterSG", 
                              "ClusterSG"
                              ], 
    },
}

通过以下方式实现:

template = Template()
for i in INSTANCE_PARAMS:
    # declared a new list
    tag_value = []
    # got the counter
    for r in range(INSTANCE_PARAMS[i]["instances"]):
        # added each one to the new list
        tag_value.append(GetAtt(ec2.Instance(INSTANCE_PARAMS[i]["name"] + str(r)), "PrivateIP")) 
    output = template.add_output([
        Output(
            str(INSTANCE_PARAMS[i]["name"]).capitalize() + "Ips",
            Description="IPs for " + str(INSTANCE_PARAMS[i]["name"]),
            # passed in the list
            Value=Join(",", tag_value,
            ),
        )
    ],
    )
print(template.to_yaml())