繁体   English   中英

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

[英]Appending to a list but list only returns last value

我有一个地铁线及其站点的值电子表格。 基本上,我试图遍历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类,您可以将每个停靠点的数据存储在dict中,每行可以是这些dict的列表,并且每个行列表都可以存在于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

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

如果同一train多次出现,看起来您的dict MTA可能会覆盖条目。

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM