I am trying to do a more elegant version of this code. This just basically appends a string to categorynumber depending on the number. Would appreciate any help.
number = [100,150,200,500]
categoryNumber = []
for i in range (0,len(number)):
if (number [i] >=1000):
categoryNumber.append('number > 1000')
elif (number [i] >=200):
categoryNumber.append('200 < number < 300')
elif (number [i] >=100):
categoryNumber.append('100 < number < 200')
elif (number [i] >=50):
categoryNumber.append('50 < number < 100')
elif (number [i] < 50):
categoryNumber.append('number < 50')
for i in range(0,len(categoryNumber)):
print i
First of all, use raw_input() instead of input() . Secondly, you could use a switch case to cut the number of lines.
No, there is no strict limit to how many elif statements you can include after an if statement. You can add as many as you need into the program, not taking into account memory or other possible limitations like hardware.
one elif statement can be there. If the condition is false, the else statement will be executed.
How about:
labels = (
(1000, 'number >= 1000'),
(200, '200 <= number < 1000'),
(100, '100 <= number < 200'),
(50, '50 <= number < 100'),
(0, 'number < 50'),
)
for i in number:
for limit, label in labels:
if i >= limit:
categoryNumber.append(label)
break
how about using bisect?
>>> import bisect
>>> categories = ['number < 50', '50 <= number < 100', '100 <= number < 200', '200 <= number < 300', '300 <= number <1000', 'number >= 1000']
>>> points = [50, 100, 200, 300, 1000]
>>> categories[bisect.bisect(points, 1000)]
'number >= 1000'
>>> categories[bisect.bisect(points, 1)]
'number < 50'
>>> categories[bisect.bisect(points, 50)]
'50 <= number < 100'
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