How to concatenate tuples

泄露秘密 提交于 2019-12-13 01:00:21

问题


I have this code:

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))

When I print((curr_route)), it gives me this result:

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

How do I make it one tuple? i.e. ('43009','43189', '43619', '42319', '28109', '42319', '28109', '28189', '03239', '03211', 'E0599', '03531')


回答1:


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

gives ('hello', 'these', 'are', 'my', 'tuples!') in my version of Python (2.7.12). Truth is, I found your question while trying to find how this works, but hopefully it's useful to you!




回答2:


Tuples exist to be immutable. If you want to append elements in a loop, create an empty list curr_route = [], append to it, and convert once the list is filled:

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)

Notice that the print is outside of the for loop, which may be simply what you were asking for since it prints a single long tuple.



来源:https://stackoverflow.com/questions/35534184/how-to-concatenate-tuples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!