我可以使用什么循环进行迭代,以便获得以下输出? [英] What loop can I use to iterate so that I can get the following output?
问题描述
这是我的代码.
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是先前定义的
filter_routes is previously defined
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))
时的输出这应该是输出.
I know it is wrong as my output should be when i print(split_routes(bus_stations))
This should be the output.
[(’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文件
routes_data = bus_stations here is a txt file that look like this
106,1,1,43009
.
.
.
106,2,51,43009
171,1,1,59009
.
.
.
171,2,73,59009
184,1,1,45009
.
.
.
184,1,52,45009
推荐答案
似乎您的问题是您将"first_station [1]"
用作字符串,而不使用其值.尝试致电 filter_routes(routes_data,first_station [1])
和 x =元组([first_station [1]] + [a])
另外,您仅使用第一个站,我的意思是要使用 ser
值,另一个问题是您需要先返回并退出函数,然后再将值存储在`resultz here这样的变量中,并在完成后返回:
seems like your problem is that you use "first_station[1]"
as a string and not use its value.
try call
filter_routes(routes_data,first_station[1])
and
x = tuple([first_station[1]] + [a])
in addition, you use only your first station, I thing you meant to use ser
value, and another problem is that you return and quit the function before you finish, store the values in variable like `resultz here, and return it when you finish:
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
并使用文件名进行调用:
and call it with the filename:
split_routes("bus_stations.txt")
这篇关于我可以使用什么循环进行迭代,以便获得以下输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!