简体   繁体   中英

Exception Handling - list index out of range

I have a list where the length of the list is dynamic. If we look at the below example, the length of the list is 2 starts from 0. I am filling in this value in an excel sheet and it works fine when the length of the list is 6 but at times the length of the list is 2 or 3 and that point of time, I get "list index out of range" which is expected. If the list is out of range, I need to fill in 0 as the Value for rest of them. How can we do this?

counts = [2, 1] #list

df1.loc[0, 'Value'] = counts[0]
df1.loc[1, 'Value'] = counts[1]
df1.loc[2, 'Value'] = counts[2]
df1.loc[3, 'Value'] = counts[3]
df1.loc[4, 'Value'] = counts[4]
df1.loc[5, 'Value'] = counts[5]

Error:

df1.loc[2, 'Value'] = counts[2]
IndexError: list index out of range

Expected Results

df1.loc[0, 'Value'] = 2
df1.loc[1, 'Value'] = 1
df1.loc[2, 'Value'] = 0
df1.loc[3, 'Value'] = 0
df1.loc[4, 'Value'] = 0
df1.loc[5, 'Value'] = 0

find the length of original list and append 0s in the list

append_len = 6 - len(count)
for i in range(append_len):
    count.append(0)


for i in range(6):
    df1.loc[i, 'Value'] = counts[i]

Input data:

>>> df1
       Key
0     Mike
1     John
2   Arnold
3   Freddy
4  Georges
5     Paul

Assign Value column:

df1["Value"] = counts + [0] * (len(df1) - len(counts))

Output result:

>>> df1
       Key  Value
0     Mike      2
1     John      1
2   Arnold      0
3   Freddy      0
4  Georges      0
5     Paul      0

http://docs.python.org/3/tutorial/errors.html?highlight=errors#handling-exceptions

example:

dictionary = {0: None, 1: None, 2: None, 3: None, 4: None, 5: None}
counts = [2, 1] #list

for i in range(len(dictionary)):
    try:
        dictionary[i] = counts[i]
    except IndexError:
        dictionary[i] = 0

for key, value in dictionary.items():
    print(key, value)

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