繁体   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