将多个for循环压缩到列表理解中

时间:2015-06-16 20:59:38

标签: python list-comprehension

如何在列表理解中执行以下操作?

asins = []
for item in data['message']['body']['titles']:
    for format in item['formats']:
        for offer in format['offers']:
            asins.append(offer['asin'])

1 个答案:

答案 0 :(得分:5)

只需将append()包含的表达式移到前面,删除冒号并在整个表达式周围添加括号:

asins = [offer['asin']
    for item in data['message']['body']['titles']
        for format in item['formats']
            for offer in format['offers']]

for语句的顺序不会改变。我们现在可以更改缩进,如果您愿意,可以加入行:

asins = [offer['asin']
         for item in data['message']['body']['titles']
         for format in item['formats']
         for offer in format['offers']]