【问题标题】:Find a value in dictionary by coordinates通过坐标在字典中查找值
【发布时间】:2022-01-04 00:29:21
【问题描述】:

我希望能够通过坐标/位置在字典中找到某个位置。 如果假设键是 x,并且每个字符代表一个 y 值,我希望能够通过询问我要查找的位置的输入来找到字典中某个位置的某个字符是什么。

1: 'Hi' 
2: 'My name is Stan'
3: 'What is your name?' 

如果你愿意放在这些地方:

(1,0) = 'H' # the H in 'Hey' 
(4,1) = Out of bounds # since key 4 do not exist
(1,2) = Out of bounds #since there is nothing after 'Hi'
(2,2) = Space #in between 'My' and 'name' 
(3,3) = t # the t in 'What'

我尝试混合一些if 循环,但没有任何好的结果。 我假设我可以使用 len() 之类的函数来查找分配给每个键的字符长度,但无法完全执行。

有这样的东西作为开始,但它需要更多。

for key, value in indexed_file.items():
    if key != row:
        print('Out of bounds')

关于如何继续执行此操作的任何提示都非常有价值。 注意:我不想使用任何导入。

【问题讨论】:

  • 你一定需要为此使用字典吗?如果你所有的键都是整数,你应该只使用一个列表......
  • 在查找特定的key 时循环遍历items 违背了拥有字典的全部目的(即,它可以让您立即查找任何键)...跨度>
  • 如果你不知道如何使用索引,你就不是真正了解 Python。以下是官方教程中的相关部分:DictionariesStrings(具体在“字符串可以被索引...”),以及Handling Exceptions
  • 只在我的问题中编了字典。这并不一定意味着在我将使用的字典中,我的键将是整数,但只是想举个例子。

标签: python loops dictionary


【解决方案1】:

您可以对字典/列表进行切片并使用try/except 捕获IndexError(和KeyError):

d = {1: 'Hi',
     2: 'My name is Stan',
     3: 'What is your name?' }

def get_letter(key, pos):
    try:
        print(d[key][pos])
    except IndexError:
        print('Out of bounds!')
    except KeyError:
        print('No Key!')

例子:

>>> get_letter(1,0)
H

>>> get_letter(2,15)
Out of bounds!

如果您希望 IndexErrorKeyError 获得相同的结果:

def get_letter(key, pos):
    try:
        print(d[key][pos])
    except (IndexError, KeyError):
        print('Out of bounds!')

【讨论】:

    【解决方案2】:

    我会做的很简单;

    d= {1:"Hi",2:"My name is stan", 3:"What is your name?"}
    input_cords = (1,1)
    
    sent = input_cords[0] #Get sentence
    if d.get(sent):
       try:
           res = d[sent][input_cords]
       except IndexError:
           print("out of bounds")
    else: 
        print("No key")
    

    【讨论】:

      【解决方案3】:

      为了好玩而没有错误处理

      dct = {1: 'Hi', 2: 'My name is Stan', 3: 'What is your name?'}
      
      x, y = 3, 0
      l = s[y:y + 1] if (s := dct.get(x, '')) else ''
      print(l if l else 'Out of bounds')
      
      W
      

      【讨论】:

        【解决方案4】:

        您可以使用字典上的get方法和字符串上的下标来获取字符,如果没有可以访问,则返回超出范围的字符串:

        def getLetter(d,k,i):
            return d.get(k,"")[i:i+1] or 'Out of Bounds'
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-11-01
          • 2023-04-05
          • 1970-01-01
          • 1970-01-01
          • 2022-12-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多