类型错误:列表索引必须是整数或切片,而不是 str [英] TypeError: list indices must be integers or slices, not str

查看:67
本文介绍了类型错误:列表索引必须是整数或切片,而不是 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


注意,如果两个列表的长度相同,也可以只zip两个列表:

import csv

dates = ['2020-01-01', '2020-01-02', '2020-01-03']
urls = ['www.abc.com', 'www.cnn.com', 'www.nbc.com']

csv_file_patch = '/path/to/filename.csv'

with open(csv_file_patch, 'w') as fout:
    csv_file = csv.writer(fout, delimiter=';', lineterminator='\n')
    result_array = zip(dates, urls)
    csv_file.writerows(result_array)

这篇关于类型错误:列表索引必须是整数或切片,而不是 str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆