通过迭代可调用列表的问题 [英] Issue with iterating through list of callable
问题描述
我有一个问题迭代python列表中的python。可卡因应该被称为一个字符串生成器。当前的行为是列表中的最后一个可调用被调用多次,因为列表中有可调用的元素。我当前的代码:
pre $ for list_of_callables:
strings =(m(s)for s in strings)
在上面的代码中,字符串最初是'Generator'类型。我也尝试了以下内容:
pre $ 对于范围(len(list_of_callables)):
strings =(list__of_callables [我](S)的字符串)
这也没有奏效,但是当我不回顾可以调用的方法,只需调用它就可以了:
strings =(list_of_callables [0](s)for s)in
string =(list_of_callables [1](s)for s in string)
<对于我来说这似乎很奇怪,因为上面的内容应该和for循环相同。
在此先感谢您的帮助和建议:)
$ div class =h2_lin>解决方案
strings =(m(s)for s in strings)
这实际上并不会调用您的可调用函数。它创建一个生成器表达式,稍后将调用 m
,使用任何 m
碰巧稍后
在循环之后, m
是最后的可调用对象。当你试图从 strings
检索一个元素时,所有嵌套的genexps都会查找 m
来计算一个值,所有找到最后一个可调用。
$ b $你可以通过使用 itertools.imap
而不是genexp来解决这个问题:
strings = itertools.imap(m,strings)
I am having an issue with iterating over a list of callables in python. The callables are supposed to be called on a generator of strings. The current behaviour is that the last callable in the list is called as many times as there are callables in the list. My current code:
for m in list_of_callables:
strings = (m(s) for s in strings)
In the above code strings is initially of type 'Generator'. I have also tried the following:
for i in range(len(list_of_callables)):
strings = (list__of_callables[i](s) for s in strings)
This has not worked either, but when I don't loop over the callables and simply call them it works just fine:
strings = (list_of_callables[0](s) for s in strings)
strings = (list_of_callables[1](s) for s in strings)
This seems strange to me as the above should be equivalent to the for loop.
Thanks in advance for your help and suggestions :).
strings = (m(s) for s in strings)
This doesn't actually call your callable. It creates a generator expression that will call m
later, using whatever m
happens to be later.
After the loop, m
is the final callable. When you try to retrieve an element from strings
, all those nested genexps look up m
to compute a value, and they all find the last callable.
You could fix this by using itertools.imap
instead of a genexp:
strings = itertools.imap(m, strings)
这篇关于通过迭代可调用列表的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!