在Python中浏览字典

时间:2016-11-06 18:22:00

标签: python python-3.x dictionary location closest

我有一个名为" locations"的词典。我为字典编写的函数以格式(d,描述,当前)设置,其中' d'引用字典,' description'引用一个字符串来描述我们正在寻找的位置,以及当前的'将我们当前在字典中的位置引用为一对坐标(x,y)。

基本上,每个位置在字典中有多个位置,每个位置都有自己的坐标对,我的目标是找到我们当前在字典中的最近位置(当前)。策略是使用距离公式来计算。

例如,如果我们正在寻找最近的加油站,我们目前在(2,2),如果两个站位于(3,1),则该功能应返回(3,1)最近的车站。 (1,4)因为(3,1)更接近(2,2)对我当前代码的任何建议都将受到赞赏。

代码:

def closest(d, description, current):
    current_location = (x, y)
    d = {(3,1):'gas', (1,4):'gas', (2,1):'food', (5,5):'food'}
    distancesFromCurrent = [distanceFormula(z, current_location) for z in places]
    for z in d:
    if z < minimum float:
        return z

我当前的代码没有错误,但肯定无法正常工作。它只是返回0,0并且我不确定如何修复它以将最近位置的坐标返回到当前位置。

2 个答案:

答案 0 :(得分:1)

在考虑了评论之后,这是我的解决方案。

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Nov  6 21:42:22 2016

@author: michaelcurrin
"""

import math

def findDistance(A, B):
    """
    In 2D space find the distance between two co-orinates is 
    known as Eucliciean distance.
    Args
        A: tuple or list of x and y co-ordinates 
            e.g. (1,2) e.g. [1,2]
        B: as A.
    Retuns
        distance: float. Decimal value for shortest between A and B
    """
    x = (A[0] - B[0])
    y = (A[1] - B[1])
    distance = math.sqrt(x**2 + y**2) # square root

    # remove comment if you want to see this outputted
    # print distance 

    return distance


def GetClosestPlace(places, loc, feature):
    """find shortest distance between current location and each locations 
    but only ones which have the desired feature"""

    # add distance from current location to each location
    for index in range(len(places)):

        # only continue if feature exists at place
        if feature in places[index]['features']:

            # calculate
            distance = findDistance(loc,
                                    places[index]['location'])
        else:
            # this is to represent n/a for now as every location needs a distance
            # for this version, so that it will not be chosen
            distance = 1000 

            # add calculated distance to existing dictionary for location
        places[index]['distance'] = distance    


    # find shortest distance and return details for that place

    allDistances = [x['distance'] for x in places]
    shortestDistance = min(allDistances)

    for place in places:
        if place['distance'] == shortestDistance:
            return place


placesList = [dict(name='foo',location=(0,3), features=['gas', 'food']),
              dict(name='bar',location=(4,6), features=['food', 'hospital']),
              dict(name='abc',location=(0,9), features=['gas','barber']),
              dict(name='xyz',location=(2,2), features=['food','barber'])
              ]

currentLocation = (5,9)
desiredFeature='food'

closestPlace = GetClosestPlace(placesList, currentLocation, desiredFeature)

print 'Current location: %s' % str(currentLocation)
print 'Desired feature: %s ' % desiredFeature
print
print 'The closest place is...'
print 'Name: %s' % closestPlace['name']
print 'Location %s' % str(closestPlace['location'])
print 'Distance %f' % closestPlace['distance']
# join multiple features in the list with commas
print 'Features: %s' % ', '.join(closestPlace['features'])

"""
OUTPUT

Current location: (5, 9)
Desired feature: food 

The closest place is...
Name: bar
Location (4, 6)
Distance 3.162278
Features: food, hospital
"""

答案 1 :(得分:0)

我认为您需要使用字典输入来计算地名的结果,使其与当前位置的距离计算为单个浮点数(或十进制数)。

这样的东西
current_location = (x, y)
distancesFromCurrent = [distanceFormula(z, current_location) for z in places]

distanceFormula将在函数中使用距离计算。

一旦你输入了所有个地方,那么你可以再做一个循环找到字典中的最小浮点值并返回其相应的地名和它的合作纵坐标(来自原始输入)。

我认为您可以在下面以这种格式从字典更改为列表输入。 (如果你有任何这样的数据已经向我们展示,那将会有所帮助)

placesList = [dict(name='abc',location=(0,3), features=['gas station','mall', 'police dept', 'fire dept']),
              dict(name='xyz',location=(4,5), features=['police dept', 'hospital']),
             #etc.
             ]

然后,您的函数会找到最接近的位置,但首先会过滤掉具有与您的描述相符的功能的位置。

希望有所帮助。