【发布时间】:2014-09-26 21:47:24
【问题描述】:
与我的上一个问题类似:是否有一种单行/Pythonic(我知道,前者不一定暗示后者)方式来编写以下嵌套 for 循环?
some_list = # list of dictionaries
for i in some_list:
for j in i['some_key']:
if j is in another_list:
i['another_key'] = True
我试过了
import itertools
for i,j in itertools.product(some_list,i):
if j is in another_list:
i['another_key'] = True
但我收到了“分配前的参考”错误,我认为这是有道理的。有什么建议?谢谢!
【问题讨论】:
-
你想在
do something区域做什么? -
想想类似:
[elm for elm in some_list if elm['key'] == value] -
#做某事很重要
-
检查 j 是否满足某些条件,如果满足则更改 i 值中的另一个键。即:for i in some_list: for j in i['some_key']: if j is in another_list: i['another_key'] = True
-
# 添加一些东西。对不起!
标签: python loops dictionary nested iteration