1
我已經TXT文件像這樣(市只是一個例子):的Python 3:在Python 3從列表中獲取信息的列表
Tokyo 0 267 308 211 156 152 216 27 60 70 75
London 267 0 155 314 111 203 101 258 254 199 310
Paris 308 155 0 429 152 315 216 330 295 249 351
Vienna 211 314 429 0 299 116 212 184 271 265 252
Tallinn 156 111 152 299 0 183 129 178 143 97 199
Helsinki 152 203 313 116 183 0 99 126 212 151 193
Stockholm 216 101 216 212 129 99 0 189 252 161 257
Moscow 27 258 330 184 178 126 189 0 87 73 68
Riga 60 254 295 271 143 212 252 87 0 91 71
Melbourne 70 199 249 265 97 151 161 73 91 0 128
Oslo 75 310 351 252 199 193 257 68 71 128 0
我想這樣的程序工作的一個例子:
Please enter starting point: Paris
Now please enter ending point: Riga
Distance between Paris and Riga is 295 km.
我是相當新的Python,我不知道如何閱讀列表中的距離列表。 我設法到目前爲止做:
cities = []
distances = []
file = open("cities.txt")
for city_info in file:
city_info = city_info.strip()
city = city_info.split()
cities.append(city[0])
distances2 = []
for dist in city[1:]:
distances2.append(int(dist))
distances.append(distances2)
# to check, if lists are good to go
print(distances)
print(cities)
file.close()
amount = len(cities)
for x in range(amount):
for y in range(amount):
startpoint = cities[x]
endpoint = cities[y]
dist1 = distances[x][y]
startpoint = input("Enter start point: ").capitalize()
if startpoint not in cities:
print("Start point doesn't exist in our database: ", startpoint)
else:
endpoint = input("Enter end point: ").capitalize()
if endpoint not in cities:
print("Start point doesn't exist in our database: ", endpoint)
else:
print("Distance between", startpoint, "and", endpoint, "is", dist1, "kilometers.")
由於我不是Python語言非常稱職的,我不知道我做錯了。例如,我想獲得城市[1]和城市[4]之間的距離,所以它應該找到距離[1] [4]的距離。
你的縮進不正確... –
出在代碼中最引人注目的很多不好的事情是東西嵌套的for循環後傳來的壓痕,這應該是在同一級別內的。 –