如何连接元组

时间:2016-02-21 08:58:05

标签: python tuples concatenation

我有这段代码:

def make_service(service_data, service_code):
    routes = ()
    curr_route = ()
    direct = ()

    first = service_data[0]
    curr_dir = str(first[1])

    for entry in service_data:
        direction = str(entry[1])
        stop = entry[3]

        if direction == curr_dir:
            curr_route = curr_route + (stop, )
            print((curr_route))

当我打印((curr_route))时,它给出了我的结果:

('43009',)
('43189', '43619')
('42319', '28109')
('42319', '28109', '28189')
('03239', '03211')
('E0599', '03531')

如何让它成为一个元组?即 ('43009','43189', '43619', '42319', '28109', '42319', '28109', '28189', '03239', '03211', 'E0599', '03531')

2 个答案:

答案 0 :(得分:1)

元组存在是不可变的。如果要在循环中追加元素,请创建一个空列表curr_route = [],附加到它,并在列表填充后转换:

def make_service(service_data, service_code):
    curr_route = []
    first = service_data[0]
    curr_dir = str(first[1])

    for entry in service_data:
        direction = str(entry[1])
        stop = entry[3]

        if direction == curr_dir:
            curr_route.append(stop)

    # If you really want a tuple, convert afterwards:
    curr_route = tuple(curr_route)
    print(curr_route)

请注意,print不在for循环中,这可能只是您要求的内容,因为它会打印一个长元组。

答案 1 :(得分:1)

tuples = (('hello',), ('these', 'are'), ('my', 'tuples!'))
sum(tuples, ())

在我的Python版本(2.7.12)中给出了('hello', 'these', 'are', 'my', 'tuples!')。事实是,我在尝试找到 这个有用的时候找到了你的问题,但希望它对你有用!