用簡單的項目開始:
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])
我認爲你需要建模你的數據,但python字典聽起來像東西你可以使用,你可以根據需要添加項目。 – Craicerjack
爲什麼你不使用列表和字典來完成這個任務?你可以動態地追加新的對象... –
我想到了它,但我不知道如何正確地組織它們使它成爲可行的。假設我有一個帶有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),我該如何動態設置它們?我根本不習慣處理動態嵌套數據......因此我的問題。 –