列表理解中的Python奇怪行为 [英] Python weird behavior in list comprehension

查看:57
本文介绍了列表理解中的Python奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def nrooks(n):#制作板子打印 n # 打印 4arr = [0 for n in range(n)] # 如果 n 的 0 变为 x 的 0,它工作正常print n # 打印 3 而不是 4nrooks(4)

为什么第二个 n 变成了 3 ,与给定的参数不同?

解决方案

Python 2

列表推导式中使用的 n 变量与传入的 n 变量相同.

理解将它设置为12,最后是3.

改为将其更改为

arr = [0 for _ in range(n)]

或(令人惊讶!)

arr = list(0 for n in range(n))

Python 3

此问题已修复.

来自 BDFL 本人:

<块引用>

我们还在 Python 3 中进行了另一项更改,以提高等效性在列表推导式和生成器表达式之间.在 Python 2 中,列表推导式将循环控制变量泄漏"到周边范围:

x = '之前'a = [x 代表 1、2、3 中的 x]print x # 这会打印 '3',而不是 'before'

<块引用>

这是列表原始实现的产物理解;这是 Python 的肮脏的小秘密"之一年.一开始是故意妥协,列出清单理解速度非常快,虽然这不是一个常见的陷阱对于初学者来说,它偶尔会刺痛人.发电机用表达式我们不能这样做.生成器表达式是使用生成器实现,其执行需要单独的执行框架...

然而,在 Python 3 中,我们决定修复肮脏的小秘密"使用与 for 相同的实现策略列出推导式生成器表达式.因此,在 Python 3 中,上面的例子(在修改使用 print(x) :-) 将打印 'before'.

def nrooks(n):
    #make board
    print n # prints 4
    arr = [0 for n in range(n)] # if 0 for n becomes 0 for x, it works fine
    print n # prints 3 instead of 4

nrooks(4)

How come the second n becomes 3 , different from the given parameter?

解决方案

Python 2

The n variable used in the list comprehension is the same n as is passed in.

The comprehension sets it to 1, 2, and then finally 3.

Instead, change it to

arr = [0 for _ in range(n)]

or (surprisingly!)

arr = list(0 for n in range(n))

Python 3

This has been fixed.

From the BDFL himself:

We also made another change in Python 3, to improve equivalence between list comprehensions and generator expressions. In Python 2, the list comprehension "leaks" the loop control variable into the surrounding scope:

x = 'before'
a = [x for x in 1, 2, 3]
print x # this prints '3', not 'before'

This was an artifact of the original implementation of list comprehensions; it was one of Python's "dirty little secrets" for years. It started out as an intentional compromise to make list comprehensions blindingly fast, and while it was not a common pitfall for beginners, it definitely stung people occasionally. For generator expressions we could not do this. Generator expressions are implemented using generators, whose execution requires a separate execution frame...

However, in Python 3, we decided to fix the "dirty little secret" of list comprehensions by using the same implementation strategy as for generator expressions. Thus, in Python 3, the above example (after modification to use print(x) :-) will print 'before'.

这篇关于列表理解中的Python奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆