Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do elif statments more elegantly if appending to array in python

Tags:

python

loops

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
like image 454
user1741339 Avatar asked Oct 12 '12 14:10

user1741339


People also ask

How do you reduce Elif in Python?

First of all, use raw_input() instead of input() . Secondly, you could use a switch case to cut the number of lines.

What is the limit to the number of Elif statements that can be implemented after an if statement?

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.

How many times can we use Elif in Python?

one elif statement can be there. If the condition is false, the else statement will be executed.


2 Answers

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
like image 107
Martijn Pieters Avatar answered Nov 15 '22 14:11

Martijn Pieters


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'
like image 42
iruvar Avatar answered Nov 15 '22 14:11

iruvar