使用在你的字典元組的列表。每個元組中的第一項是高速公路,第二項是起點。
routes = {'Chicago': [('Highway X', 'NY'), ('Highway Z', 'LA'), ('Highway AX', 'Austin'), ('Highway ZZ', 'Miami')]}
然後是微不足道的產生摘要:
for city in routes:
paths = ', '.join(sorted({route[0] for route in routes[city]}))
print("There are {} starting points to reach {}. To access this city, you can use: {}".format(len(routes[city]), city, paths))
第一行使用了一套修真刪除重複的公路,然後排序並加入他們做出一個字符串。然後,該字符串以及目標城市和路線數量將用於構造最終的摘要字符串。上面的代碼的輸出將是:
There are 4 starting points to reach Chicago. To access this city, you can use: Highway X, Highway Z, Highway ZZ
一種簡單的方法來構造routes
字典是使用列表的collections.defaultdict
。假設你的數據從一個CSV文件來:
import csv
from collections import defaultdict
routes = defaultdict(list)
with open('data.csv') as f:
reader = csv.reader(f)
for highway, start, dest in reader:
routes[dest].append((highway, start))
所以你試圖找出存儲數據,以便爲每個城市,你可以看到你可以去到其他城市的最佳方式? – jlarks32
@ jlarks32我正試圖找到一種方法來存儲所有這些數據,並像摘要一樣打印出來。 – ThomasWest