【问题标题】:Search for Keys using values in two dictionaries and output matching keys in Python使用两个字典中的值搜索键并在 Python 中输出匹配键
【发布时间】:2018-07-12 20:11:34
【问题描述】:

我已经编写了一些代码(或至少尝试过)来比较两个字典(X 和 Y)的键和值,它们具有完全相同的键但并不总是相同的值,例如 x-y 坐标图。代码应该是:

  1. 使用它们的值搜索键(要搜索的特别需要的值由预设变量提供)。
  2. 将结果键相互比较以进行匹配,如果匹配则作为输出返回。

我在所有代码中都使用了 Python 2.7(我对这门语言还很陌生),但是欢迎使用 Python 3 解决方案,但不是首选。

代码如下:

XDict = {
    "Jersey" : 0,
    "Boston" : -1,
    "York" : 0,
    "Vegas" : 1,
    "Diego" : 0
    }

YDict = {
    "Jersey" : 0,
    "Boston" : 0,
    "York" : -1,
    "Vegas" : 0,
    "Diego" : 1
    }


hereX = 0
hereY = 0

def GetLocation(Dict1, Dict2):
    locationX = "_"
    locationY = "not_"
    Location = ''

    for placeX, positionX in Dict1.iteritems():                  
        if positionX == hereX:
            locationX = placeX

    for placeY, positionY in Dict2.iteritems():
        if positionY == hereY:
            locationY = placeY

    if locationX == locationY:
        Location = locationX
        Location = locationY

    print Location

GetLocation(XDict, YDict)

预期的输出是"Jersey"

不幸的是,代码没有产生预期的输出(产生None),可能是由于 locationX 和 locationY 不匹配。 我尝试通过删除最后一个 if 块并在函数顶部插入 while locationX <> locationY: 来使用上述代码的不同形式。但这只会导致代码永远循环。

我对代码的更大目标是为 Player 类编写一个 GetLocation() 函数,该函数使用分配给每个位置的 x-y 坐标返回玩家的位置。我知道我可以使用单个字典和具有唯一值的键来实现这一点,但我更愿意使用 x-y 坐标。

我用尽了我能想到的解决方案,并尝试在 Internet 上的其他地方(包括 Stack Overflow)搜索解决方案,并找到了类似且有些有用的建议,但这些都不能解决问题,包括 this

感谢您的宝贵时间。

【问题讨论】:

    标签: python


    【解决方案1】:

    我对这个问题的看法:

    XDict = {
        "Jersey" : 0,
        "Boston" : -1,
        "York" : 0,
        "Vegas" : 1,
        "Diego" : 0
        }
    
    YDict = {
        "Jersey" : 0,
        "Boston" : 0,
        "York" : -1,
        "Vegas" : 0,
        "Diego" : 1
        }
    
    
    hereX = 0
    hereY = 0
    
    for ((n1, x), (n2, y)) in zip(XDict.items(), YDict.items()):
        if (x==hereX) and (y==hereY):
            print(n1)
            break
    

    打印:

    球衣

    但是,尚不清楚您为什么将城市名称存储在两个字典中。更好的解决方案是像这样存储数据集:

    d = {(0, 0): "Jersey",
         (-1, 0): "Boston",
         (0, -1): "York",
         (1, 0): "Vegas",
         (0, 1): "Diego"}
    

    这样你就可以通过d[(hereX, hereY)]索引它。

    【讨论】:

    • 太棒了。这正是我所需要的。如果我错了(Python 新手),请纠正我,但我猜 zip 会从两个字典的键值对中生成一组项目。就像一组一组什么的。
    • @NashDaru 是的,zip() 从它的所有参数(需要可迭代)中聚合元素 - docs.python.org/3/library/functions.html#zip
    【解决方案2】:

    您没有存储具有所需值的所有键。您需要存储所有这些,然后找到交叉点。

    XDict = {
        "Jersey" : 0,
        "Boston" : -1,
        "York" : 0,
        "Vegas" : 1,
        "Diego" : 0
        }
    
    YDict = {
        "Jersey" : 0,
        "Boston" : 0,
        "York" : -1,
        "Vegas" : 0,
        "Diego" : 1
        }
    
    
    hereX = 0
    hereY = 0
    
    def GetLocation(Dict1, Dict2):
        locationX = []
        locationY = []
        Location = ''
    
        for placeX, positionX in Dict1.items():                  
            if positionX == hereX:
                locationX.append(placeX)
    
        for placeY, positionY in Dict2.items():
            if positionY == hereY:
                locationY.append(placeY)
    
        print(set(locationX).intersection(set(locationY)))
    
    GetLocation(XDict, YDict)
    

    输出:

    {'Jersey'}
    

    【讨论】:

      【解决方案3】:

      首先请遵循一些风格指南,例如PEP8

      我有使用生成器的解决方案

      XDict = {
      "Jersey" : 0,
      "Boston" : -1,
      "York" : 0,
      "Vegas" : 1,
      "Diego" : 0
      }
      
      YDict = {
          "Jersey" : 0,
          "Boston" : 0,
          "York" : -1,
          "Vegas" : 0,
          "Diego" : 1
          }
      
      def keys_of_equal_vales(dict1, dict2):
          for key in dict1 :
              if key in dict2 and dict1[key]==dict2[key]:
                  yield key
              else :
                  continue 
          raise StopIteration 
      
      print(list(keys_of_equal_vales(XDict,YDict)))
      

      结果:

      ['Jersey']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-12
        • 1970-01-01
        • 2021-01-10
        • 2022-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多