【问题标题】:Python 3: Getting information from list in listPython 3:从列表中的列表中获取信息
【发布时间】:2015-05-24 20:32:05
【问题描述】:

我在 Python 3 中有这样的 txt 文件(城市只是示例):

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 循环之后的缩进,它应该与内部 for 处于同一级别。

标签: python list python-3.x


【解决方案1】:

试试这个:

# reading from file:
with open('cities.txt') as f:
    lines = f.readlines()

# pre-processing
indices = {line.split()[0]: i for i, line in enumerate(lines)}
distances = [line.split()[1:] for line in lines]

#user input:
start = input("Please enter starting point: ")
end = input("Now please enter ending point: ")

# evaluation:
distance = distances[indices[start]][indices[end]]

# output:
print("Distance between {start} and {end} is {distance} km.".format(**locals()))

【讨论】:

    【解决方案2】:

    另一种方法,与其他答案差别不大。

    cities = {}
    
    with open('cities.txt') as f:
        for i, line in enumerate(f.read().splitlines()):
            vals = line.split()
            cities[vals[0]] = {'index': i, 'distances': [int(i) for i in vals[1:]]}
    
    startpoint = input("Enter start point: ").capitalize()
    
    if startpoint in cities:
        endpoint = input("Enter end point: ").capitalize()
        if endpoint in cities:
            index = cities[startpoint]['index']
            distance = cities[endpoint]['distances'][index]
            print('The distance from %s to %s is %d' % (startpoint, endpoint, distance))
        else:
            print('city %s does not exist' % endpoint)
    else:
        print('city %s does not exist' % startpoint)
    

    【讨论】:

      猜你喜欢
      • 2017-05-23
      • 2022-01-14
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 2020-11-20
      相关资源
      最近更新 更多