Pythonic编写一个不使用循环索引的for循环的方法

Ada*_*ers 8 python eclipse for-loop

这与下面的代码有关,它使用for循环生成一系列随机偏移量,以便在程序的其他地方使用.

此for循环的索引未使用,这导致'违规'代码被Eclipse/PyDev突出显示为警告

def RandomSample(count):    
    pattern = []
    for i in range(count):
        pattern.append( (random() - 0.5, random() - 0.5) )

    return pattern
Run Code Online (Sandbox Code Playgroud)

所以我要么需要一种更好的方法来编写不需要循环索引的循环,或者告诉PyDev忽略未使用变量的这个特定实例的方法.

有没有人有什么建议?

YOU*_*YOU 18

仅供参考忽略PyDev中的变量

默认情况下,pydev将忽略以下变量

['_', 'empty', 'unused', 'dummy']
Run Code Online (Sandbox Code Playgroud)

您可以通过传递抑制参数来添加更多内容

-E, --unusednames  ignore unused locals/arguments if name is one of these values
Run Code Online (Sandbox Code Playgroud)

参考:http: //eclipse-pydev.sourcearchive.com/documentation/1.0.3/PyCheckerLauncher_8java-source.html

  • 如果它们*以*下划线开头,PyDev会禁止对未使用的变量发出警告.所以`_i`也会奏效. (2认同)

Rya*_*rom 5

itertools.repeat怎么样:

import itertools
count = 5
def make_pat():
    return (random() - 0.5, random() - 0.5)
list(x() for x in itertools.repeat(make_pat, count))
Run Code Online (Sandbox Code Playgroud)

样本输出:

[(-0.056940506273799985, 0.27886450895662607), 
(-0.48772848046066863, 0.24359038079935535), 
(0.1523758626306998, 0.34423337290256517), 
(-0.018504578280469697, 0.33002406492294756), 
(0.052096928160727196, -0.49089780124549254)]
Run Code Online (Sandbox Code Playgroud)


Esc*_*alo 4

randomSample = [(random() - 0.5, random() - 0.5) for _ in range(count)]
Run Code Online (Sandbox Code Playgroud)

示例输出,假设count=10您指的是标准库random()函数:

[(-0.07, -0.40), (0.39, 0.18), (0.13, 0.29), (-0.11, -0.15),\
(-0.49, 0.42), (-0.20, 0.21), (-0.44, 0.36), (0.22, -0.08),\
(0.21, 0.31), (0.33, 0.02)]
Run Code Online (Sandbox Code Playgroud)

如果您确实需要将其设为函数,则可以使用 a 进行缩写lambda

f = lambda count: [(random() - 0.5, random() - 0.5) for _ in range(count)]
Run Code Online (Sandbox Code Playgroud)

这样你就可以这样称呼它:

>>> f(1)
f(1)
[(0.03, -0.09)]
>>> f(2)
f(2)
[(-0.13, 0.38), (0.10, -0.04)]
>>> f(5)
f(5)
[(-0.38, -0.14), (0.31, -0.16), (-0.34, -0.46), (-0.45, 0.28), (-0.01, -0.18)]
>>> f(10)
f(10)
[(0.01, -0.24), (0.39, -0.11), (-0.06, 0.09), (0.42, -0.26), (0.24, -0.44) , (-0.29, -0.30), (-0.27, 0.45), (0.10, -0.41), (0.36, -0.07), (0.00, -0.42)]
>>> 
Run Code Online (Sandbox Code Playgroud)

你明白了...

  • '_' 是一个虚拟变量,Eclipse 不应该抱怨,但我不知道,因为我从未在该平台上开发过 Python。祝你好运,如果确实有抱怨,请告诉我。 (3认同)
  • 这只是将未使用的变量重命名为 _ ,所以实际上并没有更好,除非 Eclipse 特别忽略它。 (2认同)