2016-02-21 62 views
1

我有這樣的代碼:如何連接的元組

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

+0

下面的示例適用於我,是否可以在'if'節之前更改'curr_route'? – Arman

+0

我不能評論underestand,請將其添加到問題中! – Arman

+0

@drowningincode使用完整代碼更新您的問題 – Forge

回答

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
tuples = (('hello',), ('these', 'are'), ('my', 'tuples!')) 
sum(tuples,()) 

在我的Python版本(2.7.12)中給出('hello', 'these', 'are', 'my', 'tuples!')。事實是,我發現你的問題,同時試圖找到如何這個工程,但希望它對你有用!

+0

如果你想知道這個答案的性能,那麼去(這裏)[https://stackoverflow.com/questions/42059646/concatenate-tuples-using-sum]。基本上,對於小元組是可以的,但是在那裏有很多元組,你更喜歡使用itertools:'import itertools as it:元組(it.chain.from_iterable(tuples))' –

+0

另外請注意,如果你想遍歷這些值,itertool返回一個迭代器,這可以真正發揮重要作用,因爲你不必迭代元素兩次:'for it in it.chain.from_iterable(tuples):print(i)' –

相關問題