Python 类型错误:列表索引必须是整数或切片,而不是 str

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32554527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:47:31  来源:igfitidea点击:

TypeError: list indices must be integers or slices, not str

pythonarrayslistcsv

提问by Zoloom

I've got two lists that I want to merge into a single array and finally put it in a csv file. I'm a newbie with Python arrays and I don't understand how I can avoid this error :

我有两个列表要合并到一个数组中,最后将其放入一个 csv 文件中。我是 Python 数组的新手,我不明白如何避免此错误:

def fill_csv(self, array_urls, array_dates, csv_file_path):
    result_array = []
    array_length = str(len(array_dates))

    # We fill the CSV file
    file = open(csv_file_path, "w")
    csv_file = csv.writer(file, delimiter=';', lineterminator='\n')

    # We merge the two arrays in one

    for i in array_length:
        result_array[i][0].append(array_urls[i])
        result_array[i][1].append(array_dates[i])
        i += 1

    csv_file.writerows(result_array)

And got :

并得到:

  File "C:\Users\--\gcscan.py", line 63, in fill_csv
    result_array[i][0].append(array_urls[i])
TypeError: list indices must be integers or slices, not str

How can my count work ?

我的计数如何工作?

采纳答案by Alexander

First, array_lengthshould be an integer and not a string:

首先,array_length应该是一个整数而不是一个字符串:

array_length = len(array_dates)

Second, your forloop should be constructed using range:

其次,你的for循环应该使用range

for i in range(array_length):  # Use `xrange` for python 2.

Third, iwill increment automatically, so delete the following line:

第三,i会自动递增,所以删除下面这行:

i += 1

回答by Abdeali Chandanwala

I had same error and the mistake was that I had added list and dictionary into the same list (object) and when I used to iterate over the list of dictionaries and use to hit a list (type) object then I used to get this error.

我有同样的错误,错误是我将列表和字典添加到同一个列表(对象)中,当我曾经遍历字典列表并用来命中列表(类型)对象时,我曾经得到这个错误.

Its was a code error and made sure that I only added dictionary objects to that list and list typed object into the list, this solved my issue as well.

这是一个代码错误,并确保我只将字典对象添加到该列表并将键入的对象添加到列表中,这也解决了我的问题。