Python理解中是否需要局部变量? [英] Is local variable necessary in Python comprehensions?
问题描述
在Python 3.x中,我正在调用一个函数rand_foo()
,该函数每次被调用时都会返回一些随机的东西.我希望将随机结果序列存储到列表中.我正在使用以下构造:
r = [ rand_foo() for i in range(10) ]
现在我的PyCharm 3.0 IDE会继续发出警告:Local variable 'i' value is not used
.
是否有一种优雅的方法来删除不必要的变量?确实,在某些情况下,我可以使用itertools.repeat()
或类似10*[value]
的东西,但是,不能将其应用于上面的示例.
未使用变量时的约定是使用下划线:
r = [rand_foo() for _ in range(10)]
例如,请参见:下划线_作为Python中的变量名 >
我相信这会抑制您的PyCharm警告
In Python 3.x, I'm calling a function rand_foo()
which returns some random stuff each time being called. I wish to store the sequence of random results into a list. I'm using the following construct:
r = [ rand_foo() for i in range(10) ]
Now my PyCharm 3.0 IDE keeps warning: Local variable 'i' value is not used
.
Is there an elegant way of removing the unnecessary variable? Indeed, in some cases, I could use itertools.repeat()
or something like 10*[value]
, which, however, cannot be applied to my example above.
The convention when a variable is unused is to use an underscore instead:
r = [rand_foo() for _ in range(10)]
See for example: Underscore _ as variable name in Python
I believe this will suppress your PyCharm warning
这篇关于Python理解中是否需要局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!