【发布时间】: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