You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

遍历CSV构建地铁线路字典时,列表追加仅返回最后一个值的问题

Fix: Only Last Subway Line's Stops Show Up in Your Dictionary

Hey Rachel, let's sort out why you're only seeing the last line's stops in your dictionary—this is a super common pitfall when building mappings from CSV data, so we'll get it fixed quickly!

The Likely Culprit

Chances are, you're either reinitializing your dictionary (or the station list) inside your CSV loop, or you're not checking if a line already exists before adding stops. This causes every new line to overwrite the previous one, leaving only the last entry standing.

Corrected Code Example

Here's a revised version of your class that properly builds the line-to-stops mapping:

import csv

class MTALines:
    def __init__(self):
        # Initialize our dictionary once here (not inside the loop!)
        self.line_stops = {}

    def load_subway_data(self, csv_path):
        with open(csv_path, mode='r', encoding='utf-8') as csv_file:
            # Use DictReader to access columns by name (matches your CSV headers)
            reader = csv.DictReader(csv_file)
            
            for row in reader:
                line_name = row['train']  # Replace with your actual CSV column name for lines
                stop_name = row['stop_name']  # Replace with your actual CSV column name for stops
                
                # Check if the line is already in our dictionary
                if line_name not in self.line_stops:
                    # If not, create a new empty list for its stops
                    self.line_stops[line_name] = []
                
                # Add the stop to the line's list (no overwriting!)
                self.line_stops[line_name].append(stop_name)

    def get_line_stops(self, line_query):
        # Return stops for the queried line, or a friendly message if it doesn't exist
        return self.line_stops.get(line_query, f"No stops found for line '{line_query}'")

# How to use it
if __name__ == "__main__":
    mta = MTALines()
    mta.load_subway_data("your_subway_file.csv")  # Swap with your CSV file path
    print(mta.get_line_stops("L"))  # Test with a line from your data

Key Fixes Explained

  • Initialize the dictionary once: We set up self.line_stops in the class constructor, so it persists across the entire CSV loop instead of being reset every time we process a row.
  • Check for existing lines: Before adding a stop, we verify if the line is already in the dictionary. If not, we create a new list for it—this way, we're appending to existing lists instead of replacing them.
  • Use csv.DictReader: This makes it easier to reference columns by their header names (like train or stop_name) instead of relying on index numbers, which reduces errors.

What You Might Have Had Wrong

If your original code was resetting self.__points inside the loop, or assigning self.line_stops[line_name] = [stop_name] every time (instead of appending), that would overwrite the list each time, leaving only the last stop/line combo.

Give this revised code a try, and make sure the column names match exactly what's in your CSV file—you should see all stops for every line now!

内容的提问来源于stack exchange,提问作者Rachel Lopez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:04:51