以下代码旨在将一长串数字从csv转储到stat_by_symbol [symbol],以便我可以使用每个符号作为键来调用数字列表。出于某种原因,代码似乎只适用于第一个符号。有人可以帮我修复代码按预期工作吗?非常感谢。
with open('zzdata.csv', 'rb') as f:
reader = csv.reader(f)
reader.next()
for symbol in symbols:#symbols in a list
stat = []
for row in reader:
if symbol in row:
stat.append(row[8])#stat becomes long list of numbers
stat_by_symbol[symbol] = [stat]
答案 0 :(得分:2)
问题是你只能迭代reader
一次(因此只是第一个符号匹配)。
试试这个:
stat_by_symbol = {}
with open('zzdata.csv', 'rb') as f:
reader = csv.reader(f)
reader.next()
for row in reader:
for symbol in symbols:#symbols in a list
if symbol in row:
stat_by_symbol.setdefault(symbol, []).append(row[8])