Home > OS >  Iteration over two lists using index
Iteration over two lists using index

Time:03-02

I am trying to create a list of time and date at specific intervals. The times and dates are present in a time series csv and I want to write a code that extracts data from specific time intervals. I made two lists for day and hour and I am creating a new variable that that stores the date and time of interest. I have trying the following code but I get error:

day = ['01', '02', '03', '04', "05", '06', '07', '08', '09', '10', '11', '12','13','14','15','16','17','18'
      '19','20','21','22','23','24','25','26','27','28','29','30','31']
hour = ['0', '3', '6', '9', '12', '15','18','21']
year, month, day, hour = year, month, day, hour # 2016-01-01 @01:00 am
day_time = []
for i in day.index:
    for j in hour.index:
        day_time = int("".join(day[i], hour[j], "00",))
print(day_time)

TypeError                                 Traceback (most recent call last)
<ipython-input-72-15de17abf279> in <module>
      6 year, month, day, hour = year, month, day, hour # 2016-01-01 @01:00 am
      7 day_time = []
----> 8 for i in day.index:
      9     for j in hour.index:
     10         day_time = int("".join(day[i], hour[j], "00",))

TypeError: 'builtin_function_or_method' object is not iterable

can someone suggest a solution?

CodePudding user response:

index is a function, not an attribute for list instance. please refer to Data structures

also, the join function of a str data type takes iterables, refer to here

Also, as @Lecdi pointed, you should use append to add to a list instead of redefinition of the variable using =; please refer to here

to be able to do what you want to do:

day = ['01', '02', '03', '04', "05", '06', '07', '08', '09', '10', '11', '12','13','14','15','16','17','18'
      '19','20','21','22','23','24','25','26','27','28','29','30','31']
hour = ['0', '3', '6', '9', '12', '15','18','21']
year, month, day, hour = year, month, day, hour # 2016-01-01 @01:00 am
day_time = []
for day_i in day:
    for hour_i in hour:
        day_time.append(int("".join([day_i, hour_i, "00"])))
print(day_time)

CodePudding user response:

I think enumerate() would work better for you

for indexDay, valueDay in enumerate(day):
    for indexHour, valueHour in enumerate(hour):
        day_time.append(int("".join([valueDay, valueHour, "00"])))
  • Related