【问题标题】:Issue with iterating through list of callable遍历可调用列表的问题
【发布时间】: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


【解决方案1】:
strings = (m(s) for s in strings)

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

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

您可以使用 itertools.imap 代替 genexp 来解决此问题:

strings = itertools.imap(m, strings)

【讨论】:

  • 非常感谢您的帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-26
  • 1970-01-01
  • 2014-01-14
  • 1970-01-01
  • 2016-04-29
  • 1970-01-01
  • 2017-11-06
相关资源
最近更新 更多