mana lamo
mana lamo

Reputation: 41

How to filter numbers based on range?

I have a list in which some numbers are like this:

["0022", "1144", "1355", "0251"...]

These numbers represent times, 0022 represents 12:22 and so on.

Now I need to filter these times based on hours. For example, I have a range between 2 am and 4 am, therefore I need 0251 to be in this range(as it represents 02:51).

I tried doing the following:

 for i in mylist:
        if(i in range(200,400)):
            print(i)
        if(i in range(1000,1200)):
            print(i)

I did this since I thought 0251 can be interpreted as 251, but I get no output from that. The second if statment should return 1144.

I am trying to really not use ANY package or module, I want my code to be free from packages and modules... any assistance is greatly appreciated..

Upvotes: 3

Views: 321

Answers (3)

Sayse
Sayse

Reputation: 43320

The issue with your current code is you're looking if the string representing the time is in a range of integers.

The safest thing to do would be to convert it to a time and then check the range of that times hour

from datetime import datetime
for i in mylist:
    hour = datetime.strptime(i, '%H%M').hour
    if 2 < hour < 4:
         print(i)

Upvotes: 2

bv_Martn
bv_Martn

Reputation: 159

Id assume since you are using 200-400 as indices of the list (so mylist[200]-mylist[400]). instead I would do smth like

for i in mylist:
    if int(i)>200 and int(i)<400:
        print(i)
    elif int(i)>1000 and int(i)<1200:
        print(i)

Upvotes: 1

BoarGules
BoarGules

Reputation: 16941

Your list contains strings and your code is trying to filter on numeric values. Convert them to integers first.

mylist = [int(i) for i in mylist]
for i in mylist:
     ....etc...

Upvotes: 2

Related Questions