开发者

Mapping numbers

I know this is a noobish question put i could not figure it out >.< I have an number from -1000 to 1000 and I need to map it to numbers 0 to 200. I think it has to do with the map() function开发者_运维技巧 but i'm not sure.

Thanks


"0 would be 100, -500, would be 50 and 500 would be 150"

Then try the following function:

def mapNumber(a):
    return int(a + 1000) / 10

This way:

mapNumber(-1000)
> 0

mapNumber(-500)
> 50

mapNumber(0)
> 100

mapNumber(500)
> 150

mapNumber(1000)
> 200

This will map your integers into integers. And since your target range is 10 times smaller, it will map ten different numbers to the same.

If you want to get a floating point number, try this:

def mapNumber(a):
    return (a + 1000.) / 10.


Since the input range [-1000,1000] is much larger than the output range of [0,200], many numbers will end up mapping to the same value in [0,200]. The simplest way to do this would be to take the modulo of the input number mod 201. This will always give you a number in [0,200].

If you need to do this to a list of numbers, you can use the map function like so

inlist=[-1000,9,999]
outlist=map(lambda x:x%201, inlist)
print outlist

It is often preferred in Python to use a list comprehension instead.

inlist=[-1000,9,999]
outlist=[x%201 for x in inlist]
print outlist
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜