将多个 for 循环压缩为列表理解
Condense multiple for loops into list comprehension
我将如何在列表理解中执行以下操作?
asins = []
for item in data['message']['body']['titles']:
for format in item['formats']:
for offer in format['offers']:
asins.append(offer['asin'])
只需将包含 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']]
我将如何在列表理解中执行以下操作?
asins = []
for item in data['message']['body']['titles']:
for format in item['formats']:
for offer in format['offers']:
asins.append(offer['asin'])
只需将包含 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']]