【问题标题】:Why might python be interpreting my dictionary as a list?为什么 python 可能会将我的字典解释为列表?
【发布时间】:2018-07-07 01:08:42
【问题描述】:

我正在编写一个程序来对 csv 文件进行排序。它应该从文件中提取行,并根据字典中是否已经存在“捐助者”,将“捐助者”添加到字典中或将行中的信息附加到旧值。我收到错误声明:

错误声明:文件“C:/Users/riley/Desktop/Python Files/MYLATEST1.py”,第 27 行,在 捐助者[捐助者] = [[数据]] builtins.TypeError:列表索引必须是整数或切片,而不是元组

我是 python 新手,但似乎 python 将我的字典解释为一个列表。这是怎么回事?如果是这样,为什么?感谢您的帮助!

def createDonorDirect():

  listoffiles = glob.glob('C:/Users/riley/Desktop/mydata//*.csv') #glob allows you to create a list of files/folders that match wildcard expression in this case all the csv files in the directory

  # Create donors directory
  donors = {}


  for filename in listoffiles:
        with open(filename) as file:

              for line in file:

                    #  line processing stuff
                    data = line.split(',')
                    donor = ''.join(data[3,5,7])


                    # populate data structure 
                    if donor in donors:
                          donors[donor].append(data)
                    else:
                          donors[donor] = [[data]]

【问题讨论】:

  • data[3,5,7] 更有可能是罪魁祸首。其他东西可能搞砸了错误信息;也许你在 Python 打开后编辑了源代码之类的。
  • 关于如何以不同方式格式化数据[3,5,7] 的任何建议,但仍然包含识别我的“捐赠者”的所有必要信息?

标签: python list dictionary tuples


【解决方案1】:

错误的原因是您将捐赠者分配给元组值作为键,这是错误的,因为元组包含多个值。 使用代码重新生成示例问题:-

>>> data=['HI','Hello','How','are','you','my','name','is']
>>> donor = ''.join(data[3,5,7])
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    donor = ''.join(data[3,5,7])
**TypeError: list indices must be integers or slices, not tuple**
>>> 

第二个简化代码:-

>>> data[3,5,7]
Traceback (most recent call last):
  File "<pyshell#35>", line 1, in <module>
    data[3,5,7]
TypeError: list indices must be integers or slices, not tuple

【讨论】:

    【解决方案2】:

    元组声明有时可能有点令人困惑。

    例如:SOME_CONSTANT = 1,SOME_CONSTANT = (1, ) 相同。两者都是元组。

    另一方面,SOME_CONSTANT = (1) 将与 SOME_CONSTANT = 1 相同。两者都是整数。

    在你的情况下,你只需要改变:

    donor = ''.join(data[3,5,7])
    

    donor = ''.join(data[3] + data[5] + data[7])
    

    例子:

    data=['A','B','C','D','E','F','G','H']
    print ''.join(data[3] + data[5] + data[7])
    DFH
    

    【讨论】:

      猜你喜欢
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-19
      • 2013-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多