【问题标题】:TypeError: list indices must be integers or slices, not strTypeError:列表索引必须是整数或切片,而不是 str
【发布时间】:2015-12-09 20:21:36
【问题描述】:

我有两个列表,我想将它们合并到一个数组中,最后将它放入一个 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)

得到了:

  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 设为字符串,因此i 是字符而不是数字...
  • 哎呀,我看的不对……谢谢!!
  • 当我以为我正在解析 {thisthing} 而实际上我正在解析 [{thisthing}] 时,这发生在我身上;例如,我正在尝试处理字典,但实际上我正在处理列表。动态打字ftw。

标签: python arrays list csv


【解决方案1】:

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

array_length = len(array_dates)

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

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

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

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)

【讨论】:

  • 谢谢,我不知道自动递增! :) 我的代码有效,谢谢。
  • 没有什么神奇的:i 是 range(或 python 3 中的序列)返回的列表中的一个元素。哦,顺便说一句:它们都是列表,而不是数组。
【解决方案2】:

我有同样的错误,错误是我将列表和字典添加到同一个列表(对象)中,当我过去迭代字典列表并使用命中列表(类型)对象时,我曾经得到这个错误。

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

【讨论】:

    【解决方案3】:

    跟进上述 Abdeali Chandanwala answer(无法发表评论,因为代表

    TL;DR:我试图通过专注于迭代字典中的键来错误地迭代字典列表,但不得不自己迭代字典!


    我在使用这样的结构时遇到了同样的错误:

    {
       "Data":[
          {
             "RoomCode":"10",
             "Name":"Rohit",
             "Email":"rohit@123.com"
          },
          {
             "RoomCode":"20"
             "Name":"Karan",
             "Email":"karan@123.com"
          }
       ]
    }
    

    我试图将名称附加到这样的列表中-

    已修复-

    【讨论】:

      【解决方案4】:

      我在 python 中重载一个函数时收到此错误,其中一个函数包装了另一个函数:

      def getsomething(build_datastruct_inputs : list[str]) -> int:
            # builds datastruct and calls getsomething
            return getsomething(buildit(build_datastruct_inputs))
      
      def getsomething(datastruct : list[int]) -> int:
            # code
            # received this error on first use of 'datastruct'
      

      修复是不重载并使用唯一的方法名称。

      def getsomething_build(build_datastruct_inputs : list[str]) -> int:
            # builds datastruct and calls getsomething
            return getsomething_ds(buildit(build_datastruct_inputs))
      
      def getsomething_ds(datastruct : list[int]) -> int:
            # code
            # works fine again regardless of whether invoked directly/indirectly
      

      另一个解决方法是使用 python multipledispatch 包,它可以让你重载并为你解决这个问题。

      有点令人困惑,因为错误发生的位置(也不是消息)对应于什么原因。我以为我已经看到 python 原生支持重载,但现在我了解到它的实现需要用户做更多的工作。

      【讨论】:

        【解决方案5】:

        在我的情况下,我试图更改 dict 键的值,但由于我的 dict 存在于 for 循环中并且被更改为类型 list,所以我遇到了同样的错误。

        for value in source_list:
            my_dict['my_key']=some_val
            dict=list(mydict)
            exctraction0 = dict[0]
        

        我通过确保dict 的类型保持不变来解决这个问题,方法是在每个iteration 之后创建一个deepcopyre-initializing(这就是用例的全部内容)。

        copy_dict = copy.deepcopy(my_dict)
        for value in source_list:
            my_dict =copy.deepcopy(copy_dict)
            my_dict['my_key']=some_val
            dict=list(mydict)
            exctraction0 = dict[0]
        

        【讨论】:

          猜你喜欢
          • 2021-11-28
          • 1970-01-01
          • 1970-01-01
          • 2020-05-14
          • 2018-10-13
          • 2020-11-21
          相关资源
          最近更新 更多