python - 附加到列表但列表仅返回最后一个值
问题描述
我有一个地铁线路及其站点值的电子表格。基本上,我正在尝试遍历 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 字典中。使用defaultdict
for MTA 很方便,因为它会根据需要自动创建新列表。
此外,无需手动解析 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
推荐阅读
- linux - 标准库 ABI 兼容性
- windows - “启动 VM Azure”阶段等待节点可用
- jboss - JBOSS 7.1 部署顺序
- c - 如何使用 gcc 为静态库设置版本信息?
- html - Html使用Angular材料在输入字段中获取输入
- python - CS50 问题集 6(DNA)“Python”,我无法计算间歇性 DNA 序列,我的代码在小型数据库中成功,在大型数据库中失败
- string - gdb调试器中字符串的条件断点
- sql - 如何隐藏postgres中的重复记录
- c# - 在 Asp.net Core Angular Webapi 发布 IIS 上无法建立连接
- javascript - CropperJs 图像在 Vue 中很小,但在编辑后恢复正常大小