在 Python 中浏览字典

Navigating through a dictionary in Python

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

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

例如,如果我们正在寻找最近的加油站并且我们当前位于 (2,2),如果两个加油站位于(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

我当前的代码没有错误,但绝对不能正常工作。它只是 returning 0,0,我不确定如何将它固定到 return 离我们当前位置最近的位置的坐标。

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

类似

current_location = (x, y)
distancesFromCurrent = [distanceFormula(z, current_location) for z in places]

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

一旦你输入了 all 个地方,你就可以做另一个循环在字典中找到 minimum 浮点值和 return其对应的地名及其坐标位置(来自原始输入)。

我认为您可以将字典输入更改为列表输入,以采用以下格式。 (如果您已经有任何类似的数据向我们展示这也会有所帮助)

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.
             ]

然后你的函数会找到最近的位置,但首先过滤掉具有与你的描述相匹配的特征的位置。

希望对您有所帮助。

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

#!/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
"""