Home > front end >  How to perform append with if condition for multiple array
How to perform append with if condition for multiple array

Time:10-20

I am writing the following code in Python, I want to accomplish the following using a for condition

                if (datetime_obj.hour==7):
                    hour7.append(a)
                if (datetime_obj.hour==8):
                    hour8.append(a)
                if (datetime_obj.hour==9):
                    hour9.append(a)
                if (datetime_obj.hour==10):
                    hour10.append(a)
                if (datetime_obj.hour==11):
                    hour11.append(a)
                if (datetime_obj.hour==12):
                    hour12.append(a)
                if (datetime_obj.hour==13):
                    hour13.append(a)
                if (datetime_obj.hour==14):
                    hour14.append(a)
                if (datetime_obj.hour==15):
                    hour15.append(a)

hour are empty arrays.

CodePudding user response:

Make hour a list of lists, e.g., hour = [[] for _ in range(24)], such that hour[7] would give you whatever you have for hour7, etc. Then you can simply do

hour[datetime_obj.hour].append(a)

No ifs or loops.

If the values that datetime_obj.hour takes aren't consecutive values from 0 to some number, then use a dictionary of lists instead.

CodePudding user response:

It seems like your code will be greatly simplified by abandoning the specific references to each empty list (e.g. hour1, hour2). Rather, you should create some structure which holds the lists, and allows you to access them in a sensible way. The existing answer uses a nested list, which is a good option. Another way would be with a dict:

hours = {i:[] for i in range(24)}
hours[datetime_obj.hour].append(a)

hours is initialized as a dictionary where each key is an integer (representing an hour of the day) and each value is a separate empty list. You can select those empty lists by directly using datetime_obj.hour, and then append your a.

You can check out here for a relevant discussion; for both convenience and functionality, avoiding these repetitive sequential named variables is recommended!

  • Related