美文网首页
Python 2.7 与3.x中列表生成式中的临时变量作用域区别

Python 2.7 与3.x中列表生成式中的临时变量作用域区别

作者: 燕城白夜 | 来源:发表于2019-02-16 15:12 被阅读0次

在Python3.7中我们允许如下代码:

>>> dic = [{'one': 1}, {'two': 2}]

>>> for i in dic:

            a = [k for k in range(10)]

            w = sum([i for i in a])

            i['add'] = w

>>> dic

[{'one': 1, 'add': 45}, {'two': 2, 'add': 45}]

没有什么问题,列表生成式中的临时变量的作用域在该列表生成式中,不会与其它变量冲突。

接下来在Python2.7中运行相同的代码:

>>> dic = [{'one': 1}, {'two': 2}]

>>> for i in dic:

...    a = [k for k in range(10)]

...    w = sum([i for i in a])

...    i['add'] = w

... 

Traceback (most recent call last):

  File "", line 4, in

TypeError: 'int' object does not support item assignment

问题来了这时会出现冲突,导致出现我们不期望的运行结果,需多多注意。

相关文章

网友评论

      本文标题:Python 2.7 与3.x中列表生成式中的临时变量作用域区别

      本文链接:https://www.haomeiwen.com/subject/raobeqtx.html