【问题标题】:Error: List indices are supposed to be an integer but it is an integer错误:列表索引应该是整数,但它是整数
【发布时间】:2020-02-04 06:52:05
【问题描述】:

我正在尝试创建一个 while 循环,并且每次循环运行时索引都会增加 1。

我将n 设置为零,这应该告诉 python 这是一个整数。但是,当它到达if contact_list[n]['vid'] == '': 时,它会将n 视为一个字符串。

这是循环。非常感谢任何帮助:

has_more = True

n = 0

while has_more:
    parameters = urllib.parse.urlencode(parameter_dict)
    get_url = get_all_contacts_url + parameters + property_params
    r = requests.get(url= get_url, headers = headers)
    response_dict = json.loads(r.text)
    has_more = response_dict['has-more']
    contact_list.append(response_dict['contacts'])
    parameter_dict['vidOffset']= response_dict['vid-offset']
    if len(contact_list) >= max_results:
        max_results += 100
    if contact_list[n]['vid'] == '':
        break
    contact_count += 1
print('loop finished')

list_length = len(contact_list) 
print("List Length:",list_length)

print("You've succesfully parsed through {} contact records and added them to a list".format(list_length))

【问题讨论】:

  • 它将 ['vid'] 视为字符串,因为它是一个字符串。你能打印 print(contact_list[n]) 的输出吗
  • 您遇到的错误是什么,如果有的话
  • 你能分享你得到的错误吗?
  • 我也看不到你在此处增加n 的值。

标签: python python-3.x for-loop while-loop


【解决方案1】:

试试这个:

 if 'vid' in contact_list:
    if contact_list[n] == '':
     break

希望有帮助!

是的,并且意识到 n 实际上并没有增加,如果是这种情况,只需调用 0 作为列表索引,而不必分配 n=0。

【讨论】:

  • 谢谢!那行得通。关于增量,count_count 应该是 n。
猜你喜欢
  • 1970-01-01
  • 2012-12-11
  • 1970-01-01
  • 1970-01-01
  • 2015-05-03
  • 2012-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多