[英]When enumerating a list of tuples I get TypeError: 'type' object has no attribute '__getitem__'
The script below reads a CSV file and creates a list of tuples called people
. 下面的脚本读取CSV文件,并创建一个名为
people
的元组列表。 The tuple is the patron_id
(a unique string identifier) and a dictionary of person
information. 元组是
patron_id
(唯一的字符串标识符)和person
信息字典。
For a sample of data (simplified with name info removed) looking like this: 对于如下所示的数据示例(简化了名称信息):
patron_id show_id
1111MAIN MW1
2222SCOTT MW2
1111MAIN MW1
The script should output a list of tuples, that looks like this: 该脚本应输出一个元组列表,如下所示:
[ ("1111MAIN", {'patron_id': "1111MAIN", 'show_list': ["MW1", "MW2"]}), ("2222SCOTT", {'patron_id': "2222SCOTT", 'show_list': ["MW2"]}) ]
The script raises the following error in traceback: 该脚本在回溯中引发以下错误:
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]
When I test this line manually in the shell it returns the index of the tuple for which I am searching. 当我在外壳中手动测试该行时,它将返回我要搜索的元组的索引。 Why is this line failing in the script?
为什么该行在脚本中失败?
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]
You need to change enumerate[people]
to enumerate(people)
. 您需要将
enumerate[people]
更改为enumerate(people)
。 When you use brackets, python thinks you trying to access enumerate
at position people
. 当您使用方括号时,python认为您尝试访问位置
people
enumerate
。 Instead, you need to call it. 相反,您需要调用它。
Well, as stated in my comment, the problem is that you try to call the __getitem__
method of enumerate
by using square brackets, which is bound to fail because it does not have this method. 好吧,正如我的评论中所述,问题在于您尝试使用方括号调用
enumerate
的__getitem__
方法,因为它没有此方法,所以注定会失败。 To construct an enumerate object, use parentheses. 要构造枚举对象,请使用括号。
Try to pay close attention to the error messages, often they are helpful. 尝试密切注意错误消息,它们通常是有用的。 I did not need to read your whole code to find the error.
我不需要阅读您的整个代码来查找错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.