TypeError:列表索引必须是整数或切片,而不是str [英] TypeError: list indices must be integers or slices, not str
本文介绍了TypeError:列表索引必须是整数或切片,而不是str的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个列表,我想将它们合并到一个数组中,最后将其放入一个csv文件中.我是使用Python数组的新手,但我不明白如何避免出现此错误:
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 :
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)
得到了:
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
我的计数如何工作?
推荐答案
首先,array_length
应该是整数而不是字符串:
First, array_length
should be an integer and not a string:
array_length = len(array_dates)
第二,您的for
循环应使用range
构造:
Second, your for
loop should be constructed using range
:
for i in range(array_length): # Use `xrange` for python 2.
第三,i
将自动增加,因此删除以下行:
Third, i
will increment automatically, so delete the following line:
i += 1
这篇关于TypeError:列表索引必须是整数或切片,而不是str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文