Pythonic的方式来写一个for循环,不使用循环索引 [英] Pythonic way to write a for loop that doesn't use the loop index
问题描述
这个指数for循环未被使用,这导致了'违规'的代码被突出显示为Eclipse / PyDev的警告
def RandomSample (count):
pattern = []
在范围内(count):
pattern.append((random() - 0.5,random() - 0.5))
返回模式
所以我要么需要一个更好的方法来写这个循环需要一个循环索引,或者告诉PyDev忽略这个未使用的变量的具体实例。
有没有人有任何建议?
范围(count)中的_ randomSample = [(random() - 0.5,random() - 0.5)]
示例输出,对于 count = 10
和假设你的意思是标准天秤座ry 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)]
如果你真的需要把它作为一个函数,那么你可以通过使用 lambda
缩写:
f = lambda count:[(random() - 0.5,random() - 0.5)for _ in range(count)]
这样你可以这样称呼它:
$ b $ pre $
>> ;> f(1)
f(1)
[(0.03,-0.09)]
>>> f(2)
f(2)
[(-0.13,0.38),(0.10,-0.04)]
>>> (-0.38,-0.14),(0.31,-0.16),(-0.34,-0.46),(-0.45,0.28),( - 0.01, -0.18)]
>>> (0.24,-0.26),(0.24,-0.44),(10)
f ,(-0.29,-0.30),(-0.27,0.45),(0.10,-0.41),(0.36,-0.07),(0.00,-0.42)] b $ b>>>
你可以这样做...
This is to do with the following code, which uses a for loop to generate a series of random offsets for use elsewhere in the program.
The index of this for loop is unused, and this is resulting in the 'offending' code being highlighted as a warning by Eclipse / PyDev
def RandomSample(count):
pattern = []
for i in range(count):
pattern.append( (random() - 0.5, random() - 0.5) )
return pattern
So I either need a better way to write this loop that doesn't need a loop index, or a way to tell PyDev to ignore this particular instance of an unused variable.
Does anyone have any suggestions?
randomSample = [(random() - 0.5, random() - 0.5) for _ in range(count)]
Sample output, for count=10
and assuming that you mean the Standard Library random()
function:
[(-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)]
If you really need to make it a function, then you can abbreviate by using a lambda
:
f = lambda count: [(random() - 0.5, random() - 0.5) for _ in range(count)]
This way you can call it like:
>>> 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)]
>>>
you get the idea...
这篇关于Pythonic的方式来写一个for循环,不使用循环索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!