2011-12-17 57 views

回答

3

使用%操作:

>>> pi = 3.1415 

>>> angle = 2*pi+0.5 
>>> angle % (2*pi) 
0.5 

>>> angle = -4*pi + 0.5 
>>> angle % (2*pi) 
0.5 

對於角度的列表只是使用列表理解:

>>> L = [2*pi + 0.5, 4*pi + 0.6] 
>>> [i % (2*pi) for i in L] 
[0.5, 0.5999999999999996] 
>>> 
2

你可以把答案MOD 2 PI:

>>> import random 
>>> from math import pi 
>>> xx = list(random.uniform(-10,10) for i in range(4)) 
>>> xx 
[-3.652068894375777, -6.357128588604748, 9.896564215080154, -6.298659336390939] 
>>> yy = list(x % (2*pi) for x in xx) 
>>> yy 
[2.6311164128038094, 6.209242025754424, 3.613378907900568, 6.267711277968234] 
+0

我對python自己是新手,但是有沒有一個原因的調用列表(),而不是隻是在第一個地方列出它們?即xx = [random.uniform(-10,10)for i in range(4)] – 2011-12-17 16:44:34

+0

@ChadMiller我認爲'list(...)'和'[...]'在這種情況下也是一樣的。另一個是'list(...)'創建一個臨時**生成器**表達式,然後調用'list'構造函數。雖然列表理解(您的解決方案)可能會避免創建臨時對象,因此它可能更有效。 – ovgolovin 2011-12-17 16:49:00

+0

@ChadMiller:兩個原因。其中一個是歷史性的:在python 2.7中列表理解泄漏變量,這在過去引起了我的問題,所以我學會了避免它。 (在上面的例子中,如果我使用了[隨機等],那麼我們將變量賦給3)。第二個是我自然地根據生成器表達式 - 底層(random.uniform(-10 ,10)因爲我在範圍內(4)) - 我接下來用了很多,這也是習慣的力量。 – DSM 2011-12-17 16:57:17

0

考慮使用math.fmod(),因爲它比%operat處理浮點數更好要麼。見討論here