变量:
rs = {
'results': [
{'addresses': [{'State': 'NY'}, {'State': 'IL'}]},
{'addresses': [{'State': 'NJ'}, {'State': 'IL'}]}
]
}
我想获得每个结果成员的状态列表。目前我使用了以下代码:
for y in rs['results']:
for x in y['addresses']:
phy_states.append(x['state'])
我想要类似的东西:
phy_states = [x['state'] for x in y['addresses'] for y in rs['results']]
但我不知道该怎么做。上面的一行代码不起作用,因为在赋值之前引用了局部变量y。
答案 0 :(得分:9)
你几乎得到了它,你只是反过来了:
phy_states = [x['State'] for y in rs['results'] for x in y['addresses']]