簡體   English   中英

python:使列表中的元素在一定范圍內

[英]python: make the elements of a list within a certain range

鄉親們

如果我有一個浮點列表,並且想通過添加或減去2pi使它們在0到2pi的范圍內。 有什么好方法嗎?

非常感謝。

使用%運算符:

>>> 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]
>>> 

您可以采用答案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]

考慮使用math.fmod(),因為它比%運算符在處理浮點舍入方面更好。 請參閱此處的討論。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM