我可以使用什么循环进行迭代,以便获得以下输出?

时间:2014-03-11 09:33:39

标签: python loops

这是我的代码。

def split_routes(routes_data):
    first_station = routes_data[0] #(’171’, ’1’, ’1’, ’59009’)
    curr_ser = first_station[1] #171
    for entry in routes_data:
        ser = entry[0]
        a = filter_routes(routes_data,"first_station[1]") # [(’171’, ’1’, ’1’, ’59009’), ... , (’171’, ’2’, ’73’, ’59009’)]
        x = tuple(["first_station[1]"] + [a])
        c = []   
        return c.append(x) 

filter_routes先前已定义

def filter_routes(routes_data, service_code):
    data = filter(lambda entry: entry[0] == service_code,
     routes_data)
    return data

print(filter_routes(bus_stations, "106")将返回

[('106', '1', '1', '43009'), ('106', '1', '2', '43179'), .... ('106', '2', '51', '43009')]

我知道这是错误的,因为我的输出应该是print(split_routes(bus_stations)) 这应该是输出。

[(’171’, [(’171’, ’1’, ’1’, ’59009’), ... , (’171’, ’2’, ’73’, ’59009’)]),
 (’106’, [(’106’, ’1’, ’1’, ’43009’), ... , (’106’, ’2’, ’51’, ’43009’)]),
  (’184’, [(’184’, ’1’, ’1’, ’45009’), ... , (’184’, ’1’, ’52’, ’45009’)])]

routes_data = bus_stations这里是一个看起来像这样的txt文件

106,1,1,43009
.
.
.
106,2,51,43009
171,1,1,59009
.
.
.
171,2,73,59009
184,1,1,45009
.
.
.
184,1,52,45009

2 个答案:

答案 0 :(得分:0)

以下是一个可供您使用的代码段 -

import fileinput

station_routes_map = {}

for line in fileinput.input():
    route = line.strip().split(',')
    first_station = route[0]
    if first_station not in station_routes_map:
        station_routes_map[first_station] = []

    station_routes_map[first_station].append(route)

output = [(key, value) for key, value in station_routes_map.items()]

这基本上将您想要的输出存储在输出变量中。您可以根据自己的功能进行调整。可能需要在这里和那里进行修复,因为我没有测试它,但总的来说它应该运行。

更新

好的,让我解释一下。您拥有的文件格式为 -

first_station,..... rest_of_the_route ....

您正在寻找的是一个以第一站为第一站的元组列表,后面是以该第一站开头的所有路由列表。

此代码的作用是什么 -

  1. 使用fileinput模块从命令行(比方说)
  2. 读取文件
  3. 将行拆分为',',并将第一个半字节用作first_station
  4. station_routes_map字典用于存储first_station作为键,以及路由列表作为其值。
  5. 对于每一行,它会计算出first_station,然后将路由添加到station_route_map中的相应列表中(使用first_station作为密钥)
  6. 在构建地图之后,它只使用list-comprehension通过遍历所有项来从字典中准备元组列表。

答案 1 :(得分:0)

似乎您的问题是您使用"first_station[1]"作为字符串而不使用其值。 尝试打电话 filter_routes(routes_data,first_station[1])

 x = tuple([first_station[1]] + [a])
另外,你只使用你的第一站,我想你使用ser值,另一个问题是你在完成之前返回并退出函数,将值存储在变量中,如`resultz here,并返回它结束时:

result = []
for entry in routes_data:
        ser = entry[0]
        a = filter_routes(routes_data,ser) 
        x = tuple([ser] + [a])
        result.append(x) 
return result

但我会这样写:

def split_routes(routes_filename):
    stations = {}
    with open(routes_filename,"r") as routes_data:
        for line in routes_data:
            vals = line.strip().split(",") # [’171’, ’1’, ’1’, ’59009’]
            stations.setdefault(vals[0],[]).append(vals)
    result = []
    for st in stations:
        result.append((st,stations[st]))
    return result

并使用文件名调用它:

split_routes("bus_stations.txt")
相关问题