I am wondering if there is a function in Python already written for the goal that I describe later. If not, what would be the easiest way to implement. My code is attached.
Say I have a range from 1 to 999999999. Given a list of numbers like this:
[9, 44, 99]
It would return
[(1,9), (10,44), (45,99), (100, 999999999)]
If the number which are the limits are included in the input numbers, it should handle that also. Say input is
[1, 9, 44, 999999999]
The return should be:
[(1,9), (10,44), (45, 999999999)]
I could write a for loop comparing with a few conditional statement but wondering if there is a more 'smart way'.
Some data massage that might be helpful:
points = [1, 9, 44, 99]
points = sorted(list(set(points + [1, 999999999])))
UPDATED INFO: FINAL CREDITS GIVEN TO alecxe, thanks for your inspiring list comprehension solution
l = sorted(list(set(points + [1, 999999999])))
[(l[i] + int(i != 0), l[i + 1]) for i in xrange(len(l) - 1)]
You can put all that in one line but I think that is unnessary.
pandas.cut()
Example
[1,2,3,4,5,6,7,8,9,10] ---> [A,A,B,B,C,C,D,D,E,E]
R:
x <- seq(1,10,1)
cut(x, breaks = seq(0,10,2), labels = c('A','B','C','D','E'))
Python:
import pandas
x = range(1, 11, 1)
pandas.cut(x, bins=range(0, 12, 2), labels=['A','B','C','D','E'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With