追加到列表但列表仅返回最后一个值



我有一个地铁线路及其站点值的电子表格。基本上,我正在尝试迭代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

我认为你使这项任务比它需要的要复杂一些。您实际上并不需要自定义 MTALines 类,您可以将每个停靠点的数据存储在字典中,每行可以是这些字典的列表,并且每个行列表都可以存在于 MTA 字典中。使用 MTAdefaultdict很方便,因为这会根据需要自动创建新列表。

此外,无需手动解析 CSV 文件数据,有一个csv模块。通过使用它的DictReader类,我们可以让它将数据读入字典。它实际上使用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

我认为您可能需要一个defaultdict来收集MTALines实例的列表。

看起来您的字典MTA如果多次出现相同的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])

您的问题是您将__points作为实例变量。它仅适用于实例。显然,您将获得最后一个停止点或最后一个实例值。为了快速修复,请使用 __points 作为类变量,如下所示。

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

最后,您可以将列表用作MTALines.__points

最新更新