简体   繁体   English

python:使列表中的元素在一定范围内

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

folks, 乡亲们

If I have a list of floats and I want to make them within the range 0 to 2pi by adding or subtracting 2pi. 如果我有一个浮点列表,并且想通过添加或减去2pi使它们在0到2pi的范围内。 What is a good way to do it? 有什么好方法吗?

Thanks very much. 非常感谢。

Use % operator: 使用%运算符:

>>> pi = 3.1415

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

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

For a list of angles just use list comprehensions: 对于角度列表,只需使用列表推导:

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

You can take the answers mod 2 pi: 您可以采用答案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]

Consider using math.fmod() since it's better at handling rounding of floats than the % operator. 考虑使用math.fmod(),因为它比%运算符在处理浮点舍入方面更好。 See discussion here . 请参阅此处的讨论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM