如何在列表理解中执行以下操作?
asins = []
for item in data['message']['body']['titles']:
for format in item['formats']:
for offer in format['offers']:
asins.append(offer['asin'])
答案 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']]