用简单的项目开始:
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),我该如何动态设置它们?我根本不习惯处理动态嵌套数据......因此我的问题。 –