B.R*_*.Ru 2 python dictionary for-loop
变量:
rs = {
'results': [
{'addresses': [{'State': 'NY'}, {'State': 'IL'}]},
{'addresses': [{'State': 'NJ'}, {'State': 'IL'}]}
]
}
Run Code Online (Sandbox Code Playgroud)
我想获得每个结果成员的状态列表.目前我使用以下代码:
for y in rs['results']:
for x in y['addresses']:
phy_states.append(x['state'])
Run Code Online (Sandbox Code Playgroud)
我想要的东西:
phy_states = [x['state'] for x in y['addresses'] for y in rs['results']]
Run Code Online (Sandbox Code Playgroud)
但我不知道该怎么做.上面的一行代码不起作用,因为在赋值之前引用了局部变量y.
你几乎得到它,你只是相反:
phy_states = [x['State'] for y in rs['results'] for x in y['addresses']]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
165 次 |
| 最近记录: |