【问题标题】:When enumerating a list of tuples I get TypeError: 'type' object has no attribute '__getitem__'枚举元组列表时,我得到 TypeError: 'type' object has no attribute '__getitem__'
【发布时间】:2016-02-09 17:50:38
【问题描述】:

下面的脚本读取一个 CSV 文件并创建一个名为 people 的元组列表。元组是patron_id(唯一的字符串标识符)和person信息的字典。

对于如下所示的数据样本(已删除名称信息进行简化):

patron_id    show_id
1111MAIN       MW1
2222SCOTT      MW2
1111MAIN       MW1

脚本应该输出一个元组列表,如下所示:

[ ("1111MAIN", {'patron_id': "1111MAIN", 'show_list': ["MW1", "MW2"]}), ("2222SCOTT", {'patron_id': "2222SCOTT", 'show_list': ["MW2"]}) ]

脚本在回溯中引发以下错误:

File "frequency.py", line 75, in <module> main("input.csv") File "frequency.py", line 35, in main person_index = [x for x, y in enumerate[people] if y[0] == patron_id]

当我在 shell 中手动测试这一行时,它会返回我正在搜索的元组的索引。为什么这行在脚本中失败了?

import csv

def main(filename):
    people = [] #list of person tuples
    person = {} #patron info with list of unique shows

    #open csv data
    csv_file = csv.reader(open(filename, 'rb'))

    #read and define CSV data
    for record in csv_file:
        show_list = []

        patron_id = record[0]
        first_name = record[1]
        last_name = record[2]
        show_name = record[3]

        #check if this is the first row
        if len(people) == 0:
            show_list.append(show_name)
            person = (patron_id, {'patron_id': patron_id, 'first_name': first_name, 'last_name': last_name, 'show_list': show_list})
            people.append(person)

        else:

            #if this person IS in the list of people
            if any(patron_id in person for person in people) == True:
                #retrieve this person from people by finding its index          
                person_index = [x for x, y in enumerate[people] if y[0] == patron_id][0]

【问题讨论】:

  • enumerate[people]-> enumerate(people)
  • 我觉得很可笑。如果您将其作为答案发布,我会选择它。

标签: python csv tuples typeerror


【解决方案1】:

好吧,正如我的评论中所说,问题是您尝试使用方括号调用enumerate__getitem__ 方法,这必然会失败,因为它没有这个方法。要构造枚举对象,请使用括号。

尝试密切注意错误消息,它们通常很有帮助。我不需要阅读您的整个代码即可找到错误。

【讨论】:

  • 感谢您的快速帮助 - 就像我说的,我觉得自己很傻!
【解决方案2】:

您需要将enumerate[people] 更改为enumerate(people)。当你使用方括号时,python 认为你试图在位置people 访问enumerate。相反,您需要调用它。

【讨论】:

  • 我将 timgeb 标记为答案,因为他击败了你,但作为评论 - 这完全正确。
猜你喜欢
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 2022-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-26
相关资源
最近更新 更多