简体   繁体   中英

How to set a dynamic range in a for loop (avoid index out of range when removing an item during the loop)?

I have a dictionary that holds many dataframes I am trying to concatenate and reduce my dictionary by finding keys that are matching in their content and to concatenate such, after every concat i would like to remove one of the keys in the dictionary. let's assume that each key is named after the day that the dataframe was created, i would like to concatenate all the lists for 2018... The problem is i get IndexError: list index out of range (I guess after deleting one key as the range of the for loop remains the same) What I would like to do is that after every time I delete, the range is being adjusted by -1 so I wont have this problem. any ideas?

for i in range(len(dict)-2):
        for j in range(1,(len(dict)-1)):
           if (list(dict.keys())[i][4:12] ==list(dict.keys())[j][4:12]):
               dict[list(dict.keys())[i]] = pd.concat([dict[list(dict.keys()[i]],dict[list(dict.keys()[j]],sort= False)
del dict[list(dict.keys())[j]

IndexError: list index out of range

Since elements in a list move to the left after you remove anything in front of them, you can just loop through your list from the back. Here is a simple example which makes it easier to understand than your code:

>>> l = [1, 2, 3, 4, 5, 6]
>>> for i in range(len(l)):
    real_i = len(l)-i-1
    if l[real_i] % 2 == 0:
        del l[real_i]


>>> l
[1, 3, 5]

Here I am removing every element from the list which can be divided by 2. Since I calculate the index starting from the last one using real_i = len(l)-i-1 , it doesn't matter if I delete elements from the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM