遍历可调用列表的问题

Issue with iterating through list of callable

我在遍历 python 中的可调用项列表时遇到问题。应该在字符串生成器上调用可调用对象。当前行为是列表中的最后一个可调用项被调用的次数与列表中的可调用项一样多。我当前的代码:

for m in list_of_callables:
    strings = (m(s) for s in strings)

在上面的代码中,字符串最初是 'Generator' 类型。我还尝试了以下方法:

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 循环。

提前感谢您的帮助和建议:)。

strings = (m(s) for s in strings)

这实际上并没有调用您的可调用对象。它创建一个生成器表达式,稍后将调用 m使用任何 m 稍后发生的 .

循环后,m是最终的可调用对象。当您尝试从 strings 检索元素时,所有这些嵌套的 genexp 查找 m 来计算一个值,并且它们都找到最后一个可调用的。

您可以使用 itertools.imap 而不是 genexp 来解决此问题:

strings = itertools.imap(m, strings)