【发布时间】:2016-10-01 05:22:41
【问题描述】:
我在迭代 python 中的可调用列表时遇到问题。可调用对象应该在字符串生成器上调用。当前的行为是列表中的最后一个可调用对象被调用的次数与列表中的可调用对象一样多。我当前的代码:
for m in list_of_callables:
strings = (m(s) for s in strings)
在上面的代码中,字符串最初是“生成器”类型。我还尝试了以下方法:
for i in range(len(list_of_callables)):
strings = (list__of_callables[i](s) for s in strings)
这也不起作用,但是当我不遍历可调用对象并简单地调用它们时,它就可以正常工作:
strings = (list_of_callables[0](s) for s in strings)
strings = (list_of_callables[1](s) for s in strings)
这对我来说似乎很奇怪,因为上面应该等同于 for 循环。
提前感谢您的帮助和建议:)。
【问题讨论】:
-
这听起来像是late binding closures的一集
-
你知道
generator是什么意思吗?我认为您想使用list comprehension 而不是generator expression。 -
这里的预期行为是什么?我对您在生成器内部和外部重复使用标识符
strings感到困惑。这让你很难理解代码背后的原因。 -
@Two-BitAlchemist 是的,确实如此。谢谢你的帮助:)。
-
@HåkenLid 预期的行为是通过使用回调函数来修改字符串(即向它们附加内容等)。
标签: python string python-2.7 for-loop callable-statement