【问题标题】:python list comprehension VS for behaviourpython列表理解VS行为
【发布时间】:2011-05-03 14:43:08
【问题描述】:

编辑:我的愚蠢逻辑领先于我。 none 只是理解调用的返回。 好的,我在 python 中运行了一些测试,并且在执行顺序上遇到了一些差异,这让我了解了它是如何实现的,但是我想由你们这些优秀的人运行它来看看如果我是对的,或者还有更多。考虑这段代码:

>>> a = ["a","b","c","d","e"]
>>> def test(self,arg):
...     print "testing %s" %(arg)
...     a.pop()
... 
>>>[test(elem) for elem in a]
testing a
testing b
testing c
[None, None, None]
>>> a
['a', 'b']
#now we try another syntax
>>> a = ["a","b","c","d","e"]
>>> for elem in a:
...     print "elem is %s"%(elem)
...     test(elem)
... 
elem is a
testing a
elem is b
testing b
elem is c
testing c
>>> a
['a', 'b']
>>> 

现在这告诉我 a: 中的 for elem 获取下一个可迭代元素然后应用主体,而理解在实际执行函数中的代码之前以某种方式调用列表的每个元素上的函数,因此修改列表从函数(pop)导致]none,none,none]

这是对的吗?这里发生了什么?

谢谢

【问题讨论】:

  • test() 不返回任何内容,因此它返回 None。 (顺便说一句,您应该删除self 参数。)
  • 是的,我只是在玩,我想看看它们是否真的等价……但是这里的执行顺序有些问题。
  • 在迭代集合时调整集合的大小(添加或删除项目)是一种应受惩罚的罪行。
  • 是的,当然,我不是在争论这个
  • forloop 和列表理解在这种情况下是否具有相同的效果?他们都打印“测试a,测试b,测试c”和a==['a','b']。有什么区别???

标签: python list-comprehension


【解决方案1】:

您的test 函数没有return 语句,因此在列表推导中使用它会产生Nones 的列表。交互式 python 提示符会打印出最后一条语句返回的任何内容。

例子:

>>> def noop(x): pass
... 
>>> [noop(i) for i in range(5)]
[None, None, None, None, None]

因此,您的问题中的列表理解和 for 循环的工作方式确实没有区别。

【讨论】:

    【解决方案2】:
    >>> a = ["a","b","c","d","e"]
    >>> i = iter(a)
    >>> next(i)
    'a'
    >>> a.pop()
    'e'
    >>> next(i)
    'b'
    >>> a.pop()
    'd'
    >>> next(i)
    'c'
    >>> a.pop()
    'c'
    >>> next(i)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    StopIteration
    >>>
    

    【讨论】:

      【解决方案3】:

      它必须到达"c",然后用完列表中的元素。由于test 没有返回任何内容,您将得到[None, None, None]

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-18
        • 2015-10-27
        • 1970-01-01
        • 2017-10-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多