下面的脚本读取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]
答案 0 :(得分:3)
您需要将enumerate[people]
更改为enumerate(people)
。当您使用括号时,python认为您尝试访问enumerate
位置的people
。相反,你需要调用它。
答案 1 :(得分:3)
好吧,正如我的评论中所述,问题是您尝试使用方括号调用__getitem__
enumerate
方法,因为它没有此方法,因此必然会失败。要构造枚举对象,请使用括号。
尝试密切关注错误消息,通常它们很有帮助。我不需要阅读您的整个代码来查找错误。