首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python函数工作,但排序错误。

Python函数工作,但排序错误。
EN

Stack Overflow用户
提问于 2017-08-31 13:13:40
回答 2查看 683关注 0票数 1

我要写一个函数的旅游长度(旅游,地点),返回的总距离作为一个浮动的给定旅游,即旅行地点之间的距离之和。例如,旅游("ngv“、”馈方“、”我的酒店“)的总距离为4.0。

我的守则:

代码语言:javascript
复制
import math

def distance(x1, y1, x2, y2):                                                    
    return math.sqrt((x2 - x1)**2 + (y2 - y1)**2) 


def tourlength(tour, locations):
    DBP = []
    tour_list = [i for i in locations if i[0] in tour]
    coordinate = [i[1:] for i in tour_list]
    x_coordinate = [i[0] for i in coordinate]
    y_coordinate = [i[1] for i in coordinate]
    a = 0
    b = 1
    j = 0
    while j <= (len(tour_list)-2):
      distances = distance(x_coordinate[a], y_coordinate[a], x_coordinate[b], y_coordinate[b])
      DBP.append(distances)
      a += 1
      b += 1
      j += 1
    return sum(DBP)

假设我的函数定义为:

代码语言:javascript
复制
tourlength(["ngv", "fed square", "myhotel"], [("ngv", 4, 0), ("town hall", 4, 4),("myhotel",  2, 2), ("parliament", 8, 5.5), ("fed square",  4, 2)]))

返回的值是4。但是,我的函数返回值4.82842712474619,这是旅游列表["ngv", "myhotel", "fed square"]的值。

我知道我的代码确实能工作,但没有按照我认为是基于这个部分的正确顺序来工作:tour_list = [i for i in locations if i[0] in tour],但是我不确定在没有导入其他内置的python函数的情况下对它进行调整。

提前感谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-08-31 13:41:48

您的tour_list是基于位置的订单,而不是基于旅游。使用dict更好地实现这一点。

代码语言:javascript
复制
import math

def distance(x1, y1, x2, y2):                                                    
    return math.sqrt((x2 - x1)**2 + (y2 - y1)**2) 


def tourlength(tour, locations):
    DBP = []
    coordinates = {}
    for item in locations:
      coordinates[item[0]] = item[1:]
    j = 0
    while j <= (len(tour)-2):
      dest_1 = tour[j]
      dest_2 = tour[j + 1]
      distances = distance(coordinates[dest_1][0], coordinates[dest_1][1], coordinates[dest_2][0], coordinates[dest_2][1])
      DBP.append(distances)
      j += 1
    return sum(DBP)
票数 0
EN

Stack Overflow用户

发布于 2017-08-31 13:25:19

您在各个地点进行迭代,因此旅游按照位置列表的顺序排列。我建议您将位置转换为字典,类似于{"ngv": (4,0), ..}广告,将行tour_list = [i for i in locations if i[0] in tour]转换为

代码语言:javascript
复制
tour_list = [i for i in tour if i in locations.keys()]

但是你可以让你的代码更好。这里的字典很有用

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45982325

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档