将列表添加到元组中?

时间:2014-03-10 17:01:18

标签: python list tuples

这些是先前定义的。

def get_service_code(service):
    return str(service[0])

service_106_data = filter_routes(bus_stations, "106")  #[('106', '1', '1', '43009'), ('106', '1', '2', '43179'), .... ('106', '2', '51', '43009')]
service_106 = make_service(service_106_data, "106")  # ('106', [['43009', '43179',...'43009']])
print(get_service_code(service_106))  --> should return 106

bus_stations这里是一个txt文件,其中包含一个像这样的数字列表

106,1,1,43009
106,1,2,43179
.
.
.
106,2,1,03239
106,2,2,03211
.
.
.
106,2,50,43171
106,2,51,43009

然后这也是先前定义的

def get_route(service, direction):
    return str(service[int(direction)][0])

print(get_route(service_106, '1'))

应该返回

['43009', '43179', '43189', '43619', '43629', '42319', '28109', '28189', '28019', '20109', '17189', '17179', '17169', '17159', '19049', '19039', '19029', '19019', '11199', '11189', '11401', '11239', '11229', '11219', '11209', '13029', '13019', '09149', '09159', '09169', '09179', '09048', '09038', '08138', '08057', '08069', '04179', '02049', 'E0200', '02151', '02161', '02171', '03509', '03519', '03539', '03129', '03218', '03219']

  def make_service(service_data, service_code):
    routes = []
    curr_route = []

    first = service_data[0]  #('106', '1', '1', '43009')
    curr_dir = first[1]   # '1'
    l = list(curr_dir)    # ['1']


    for entry in service_data:
        direction = entry[1] #'1'
        stop = entry[3]  #'43009'

        if direction == curr_dir:   
            curr_route.append(stop) #[43009]
        else:
            routes.append(curr_route)   #[[]]
            curr_route = [stop]         #['43009']
            curr_dir = direction       #not '1'
            l.append(list(direction))  # ['1', __]


    routes.append(curr_route)   #[['43009']]

    #modify this code below
    return (service_code,curr_route)  #("106", [['43009']]) 

service_106 = make_service(service_106_data, "106")

print(service_106)

print(get_service_code((service_106))) # should return 106

打印的预期输出(service_106)是

('106',['1','2'],['03239', '03211', 'E0321', 'E0564', '03222', 'E0599', '03531', '03511', '03501', '02051', '02061', '04111', '04121', '08041', '08031', '08111', '08121', '09059', '09022', '09111', '09121', '09131', '09141', '13011', '13021', '11201', '11211', '11221', '11231', '11419', '11409', '11181', '11191', '19011', '19021', '19031', '19041', '17151', '17161', '17171', '17181', '20101', '28011', '28181', '28101', '42311', '43621', '43611', '43181', '43171', '43009'])

['1','2'] 假设是新添加的列表,我不仅应该能够添加 ['1','2'] 我应该能够添加['A4'] / ['A2','A4']或​​其他非数字列表 我只想在代码中添加新行并修改最后一行。

2 个答案:

答案 0 :(得分:0)

我认为你只需要

return (service_code, list(set(zip(*service_data)[1])), curr_route)  #("106", [['43009']]) 

虽然很难说(但这确实给出了预期的输出)

使用

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

结果为('106', ['1', '2'], ['43009'])

答案 1 :(得分:0)

我想你可以使用:

return tuple([service_code] + service_data)