首页 > 解决方案 > 为什么我得到'int'不可下标

问题描述

我希望它打印出来的地方:

'HTTP 错误

成功错误

401:未经授权'

所以基本上,我创建了一个名为 def create_error_dictionary(error_codes,error_description) 的函数,它的作用是获取 error_codes 的数字和 error_descriptions 中的字符串,并将数字作为字典的键,并将字符串作为字典的值。然后它把字典返回到主目录,在 def get_error_code_information (error,error_code_dictionary, error_category_dictionary) 中使用。这个函数打印出

HTTP 错误

成功错误

401:未经授权

2 .split() 部分,是拆分'status:HTTP/2.401',使列表看起来像这样: ['2', '401'] 之后,我做了一个for循环,来改变类型从 str 到 int,以便我可以在我的打印语句中使用它来进行索引。但问题是,当我运行时,有一个 TypeError: 'int' object is not subscriptable。我被困在如何打印这些信息上,而且我想知道是否有一种方法可以让我从 create_error_dictionary 转到 get_error_code_information 而无需进入主目录。

def create_error_dictionary(error_codes, error_descriptions):
    error_code_dict = {}
    v = 0
    for i in error_codes:
        error_code_dict[i] = error_descriptions[v]
        v += 1

    return error_code_dict
    


def get_error_code_information(error, error_code_dictionary, error_category_dictionary):

    split_num_HTTP_error = error.split('/')
    split_num_error = split_num_HTTP_error[1].split('.')
    for char in split_num_error:
        split_int_error = int(char)
    print(f'HTTP ERROR\n {error_category_dictionary[split_int_error[0]]} Error\n {split_int_error[1]}:{error_code_dictionary[split_int_error[1]]}')
          
          
          

          
error_codes = [400, 401, 402]

error_descriptions = ['Bad Request', 'Unauthorized', 'Payment Required']

error_category_dictionary={1:'Information', 2:'Successful', 3:'Redirection'}


a = create_error_dictionary(error_codes, error_descriptions)

print(get_error_code_information('status:HTTP/2.402',a, error_category_dictionary))

标签: python-3.xlistfunctiondictionaryfor-loop

解决方案


你有一个循环:

for char in split_num_error:
    split_int_error = int(char)

接下来是执行以下操作的代码:

print(f'HTTP ERROR\n {error_category_dictionary[split_int_error[0]]} Error\n {split_int_error[1]}:{error_code_dictionary[split_int_error[1]]}')

请注意它split_int_error在索引 0 和 1 处的索引方式,尽管split_int_error它是单个 (not subscriptable) int

您是否可能打算执行以下操作:

split_int_error = [int(char) for char in split_num_error]

所以它是list的所有整数转换组件中的一个split_num_error


推荐阅读