2017-06-22 69 views
0

我試圖找到一種方法來創建可變數量的變量與子變量來存儲數據,然後再解析它進行排序。創建未知數量的「嵌套」變量

讓我們來深入一點:我需要存儲可變數量的下一個離站數據,用於從交通線路的變量列表的兩個方向停靠。解析一個feed,每次我用一個for循環迭代一個車輛的一個車輛,並且每個車站在一個給定的方向上都有一個車輛,所以我不知道在開始時會有多少,哪些線路,停止和離開。有。

我不知道如何創建相關變量以便能夠存儲所有這些數據,然後能夠使用行,方向和停止名稱作爲關鍵字在每個站點上迭代下一個站點。

你能幫我找到適當的結構使用和如何?

感謝您的幫助。

+2

我認爲你需要建模你的數據,但python字典聽起來像東西你可以使用,你可以根據需要添加項目。 – Craicerjack

+0

爲什麼你不使用列表和字典來完成這個任務?你可以動態地追加新的對象... –

+0

我想到了它,但我不知道如何正確地組織它們使它成爲可行的。假設我有一個帶有W和X站點的「C」線,每個方向各有兩個出發時間(W,出站:11:00,12:00; X出站:11:30,12:30; W, Inbound:11:45,12:45; X,inbound 12:15,13:15)和Y和Z的「B」線停止,每個方向上有兩個出發時間(Y,出站: 12:00; Z,出港:11:30,12:30; Y,入境:11:45,12:45; Z,入境12:15,13:15),我該如何動態設置它們?我根本不習慣處理動態嵌套數據......因此我的問題。 –

回答

1

用簡單的項目開始:

vehicles = ('vehicle 1', 'vehicle 2') 

# Simulating 2 departures list 
dep_vehicle_1 = [str(time).zfill(2)+':00' for time in range(10)] 
dep_vehicle_2 = [str(time).zfill(2)+':00' for time in range(5)] 

# Create a dictionary to start collecting departures times 
departures_list = {} 

# Filling the departures dictionary with vehicles 
for vehicle in vehicles: 
    departures_list[vehicle] = [] 
    # Output: 
    # {'vehicle 1': [], 'vehicle 2': []} 

# Later, to add (n) departures time, just launch the loop for each vehicle: 
departures_list['vehicle 1'] += dep_vehicle_1 
departures_list['vehicle 2'] += dep_vehicle_2 

# If later you need to iterate over time, you can do: 
for time in departures_list['vehicle 1']: 
    print(time) 

另外需要注意的是,你可以嵌套一個字典到詞典:

departures_list['another_set'] = {'option1': 'value1', 'option2': 'value2'} 
print(departures_list) 
''' 
{'vehicle 1': ['00:00', '01:00', '02:00', '03:00', '04:00', 
'05:00', '06:00', '07:00', '08:00', '09:00'], 
'vehicle 2': ['00:00', '01:00', '02:00', '03:00', '04:00'], 
'another_set': {'option1': 'value1', 'option2': 'value2'}} 
''' 

print(departures_list['another_set']) 
# {'option1': 'value1', 'option2': 'value2'} 

print(departures_list['another_set']['option1']) 
# value1 

如果你想遍歷在未知數量的車輛你字典你可以:

for key in departures_list: 
    print(key, departures_list[key])