[英]How to write this elegantly in Python?
我試圖用Python編寫此循環,但感到困惑。 基本上我有一個起始角度90,我想使用-90到90的范圍,迭代10次。 循環完成后,我想將角度除以一半,然后重復使用-45至45的過程,進行10次迭代,依此類推。
必須包含最終值,因此90是第一個循環的最后一個值,然后45是第二個循環的最后一個值,依此類推。
如何用Python優雅高效地編寫代碼?
startAngle = 90
for i in range(5):
for x in range(10):
print values from -startAngle to startAngle (startAngle included)
startAngle = startAngle / 2
def angles(x):
return [ i * x / 5 - x for i in xrange(11)]
angles(90)
返回[-90, -72, -54, -36, -18, 0, 18, 36, 54, 72, 90]
angles(45)
返回[-45, -36, -27, -18, -9, 0, 9, 18, 27, 36, 45]
您現在可以遍歷返回值,它是一個列表。
我的angles
方法中有十個步驟返回11個值。
如果您需要其他步驟:
def angles(angle, steps):
return [ i * angle * 2 / (steps - 1) - angle for i in xrange(steps)]
angles(90, 5)
返回[-90, -45, 0, 45, 90]
您的麻煩似乎正在翻譯:
print values from -startAngle to startAngle (startAngle included)
進入Python。 range
可以輕松處理此問題:
print(list(range(-startAngle, startAngle+1)))
除了您似乎恰好需要10個值-這給出2*startAngle+1
值( range(-a, a)
有2a個值,並且還有1個值),並放入示例代碼將打印出所有這十次。
一個正確挑選step
參數range
可以保證它會給numvalues
元素-你想要的工序價值觀的非數step
ED范圍內你想要的值,圍捕因為數除以range
要整數:
print(list(range(-startAngle, startAngle+1, math.ceil((2*startangle+1)/numvalues))
因此,numvalues = 10和startAngle = 45為您提供:
list(range(-45, 46, math.ceil((2*45+1)/10)))
[-45, -35, -25, -15, -5, 5, 15, 25, 35, 45]
請注意,我假設您正在使用Python3。在Python 2中,您可以執行以下操作:
from __future__ import division
或將numvalues
設置為10.
,執行range(...)
而不是list(range(...))
,並執行int(ceil(...))
而不是ceil(...)
具有相同的效果。
如果需要處理浮點數,另一種方法也可以正常使用,它是使用numpy.linspace-它使用num
參數而不是step
,並且默認情況下包括其端點-因此,
numpy.linspace(-startAngle, startAngle, num=10)
將直接給您您想要的。
def ang_rec(angel):
for i in range(10):
if i == 9: ang_rec(angel/2)
print "do something another"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.