在this Python documentation以下用作生成器表达式的示例:
dict((fn(i+1), code)
for i, code in enumerate('FGHJKMNQUVXZ')
for fn in (int, str))
>> {1: 'F', '1': 'F', 2: 'G', '2': 'G', 3: 'H', '3': 'H', 4: 'J',...}
我不明白第二个for
循环,for fn in (int, str)
是如何将int 值变成一个字符串并添加一个额外的条目到字典。
我找到了 this Stack Overflow question ,但在这种情况下,我仍然无法理解第二个 for
循环的工作原理。
最佳答案
“展开”生成器表达式中的循环,并将它们编写为独立的 for
循环可能会有所帮助。为此,您将所有 for (variable) in (iterable)
语句以相同的顺序放在不同的行中,但是将内容从前面移到最里面的主体中 for环形。像这样,一般来说:
thing for a in a_list for b in b_list for c in c_list
成为
for a in a_list:
for b in b_list:
for c in c_list:
thing
除了当你执行生成器表达式时,所有的 thing
都会自动进入列表或字典或其他任何东西。在你的情况下,
dict((fn(i+1), code)
for i, code in enumerate('FGHJKMNQUVXZ')
for fn in (int, str))
成为
for i, code in enumerate('FGHJKMNQUVXZ'):
for fn in (int, str):
(fn(i+1), code)
除了所有的元组将被转换成一个dict
。
正如其他答案所解释的那样,您可以跟踪这两个 for
循环的执行。首先,外层循环将 i
设置为 0
并将 code
设置为 'F'
,在其中,内层循环loop 将 fn
设置为 int
然后设置为 str
,所以你得到
int(0+1, 'F')
str(0+1, 'F')
然后继续下一个 i
和 code
。
关于python - 字典生成器中的多个 'for' 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41340400/