我有一张地铁线路及其站点值的电子表格。基本上,我试图迭代CSV文件,以便当您输入一条火车线时,它会吐出所有的停靠点。我这样做是通过创建一个字典,其中键是火车线,值是停靠列表。我告诉要追加的功能但是当我打印时它只显示工作表上的最后一个值。谢谢你的帮助!
import os;
class MTALines:
def __init__(self,train="",stop_name=""):
self.__points=[];
self.train=train;
self.stop_name=stop_name;
def addLine(self,stop_name):
self.__points.append(self.stop_name);
def __repr__(self):
string=""
for item in self.__points:
string+=item+","
return string
def main():
inFile = open("hw8 - mta train stop data.csv", "r")
header = inFile.readline();
MTA={};
for line in inFile:
parts = line.split(',');
stop_id=parts[0]
train=stop_id[0]
stop_name=parts[2]
getstops = MTALines(train,stop_name);
getstops.addLine(stop_name);
MTA[train] = getstops;
trainline=""
while trainline!="done":
trainline=input("Please enter a train line, or 'done' to stop: ")
print(trainline,"line:",MTA[trainline])
main();
更新
这里要求的是CSV文件的几行:
stop_id,stop_code,stop_name,stop_desc,stop_lat,stop_lon,zone_id,stop_url,location_type,parent_station
101,,Van Cortlandt Park - 242 St,,40.889248,-73.898583,,,1,
101N,,Van Cortlandt Park - 242 St,,40.889248,-73.898583,,,0,101
101S,,Van Cortlandt Park - 242 St,,40.889248,-73.898583,,,0,101
209S,,Burke Av,,40.871356,-73.867164,,,0,209
210,,Allerton Av,,40.865462,-73.867352,,,1,
210N,,Allerton Av,,40.865462,-73.867352,,,0,210
210S,,Allerton Av,,40.865462,-73.867352,,,0,210
答案 0 :(得分:2)
我认为你让这个任务比它需要的更复杂一点。您实际上并不需要自定义MTALines类,您可以将每个停靠点的数据存储在dict中,每行可以是这些dicts的列表,并且每个行列表都可以存在于MTA dict中。为{MTA}使用defaultdict
很方便,因为它会根据需要自动创建新列表。
此外,无需手动解析CSV文件数据,还有csv
模块。通过使用它的DictReader
类,我们可以让它将数据读入dict。它实际上使用OrderedDict来保存字段的顺序。
这是我的代码版本。我更改了CSV文件的名称,因为我讨厌带有空格的文件名。 ;)因为我们正在使用MTA列表的默认值,如果我们尝试查找不存在的行,我们会得到一个空列表。
import csv
from collections import defaultdict
def main():
MTA = defaultdict(list)
with open("train_data.csv", "r") as inFile:
reader = csv.DictReader(inFile)
#print(reader.fieldnames)
for row in reader:
# Get the line id from the stop id
train = row['stop_id'][0]
# Extract the desired fields to a new dict
data = {'stop_id': row['stop_id'], 'stop_name': row['stop_name']}
MTA[train].append(data)
while True:
line_id = input("Please enter a train line, or 'done' to stop: ")
if line_id == "done":
break
print("line:", line_id)
for stop in MTA[line_id]:
print(stop['stop_id'], stop['stop_name'])
main()
演示输出
Please enter a train line, or 'done' to stop: 1
line: 1
101 Van Cortlandt Park - 242 St
101N Van Cortlandt Park - 242 St
101S Van Cortlandt Park - 242 St
Please enter a train line, or 'done' to stop: 2
line: 2
209S Burke Av
210 Allerton Av
210N Allerton Av
210S Allerton Av
Please enter a train line, or 'done' to stop: 3
line: 3
Please enter a train line, or 'done' to stop: done
答案 1 :(得分:1)
我认为您可能需要defaultdict
来收集MTALines
个实例的列表。
如果多次出现相同的MTA
,您的dict train
可能会覆盖条目。
试试这个:
from collections import defaultdict
...
def main():
inFile = open("hw8 - mta train stop data.csv", "r")
header = inFile.readline()
MTA = defaultdict(list) # create defaultdict here
for line in inFile:
parts = line.split(',')
stop_id = parts[0]
train = stop_id[0]
stop_name = parts[2]
getstops = MTALines(train,stop_name)
getstops.addLine(stop_name)
MTA[train].append(getstops) # append to list of MTALines
...
现在'问题'可能是如何格式化MTA
集合中的条目:
print(trainline, "line:", MTA[trainline])
答案 2 :(得分:0)
您的问题是您将__points作为实例变量。它仅适用于实例。显然,您将获得最后一个停止或最后一个实例值。要快速修复,请使用__points作为类变量,如下所示。
.example-class{
grid-column: 1;
grid-row: 0.333333;
}
最后,您可以将列表用作class MTALines:
__points=[];
def __init__(self,train="",stop_name=""):
self.train=train;
self.stop_name=stop_name;
def addLine(self,stop_name):
MTALines.__points.append(self.stop_name);
def __repr__(self):
string=""
for item in self.__points:
string+=item+","
return string