【问题标题】:How can I access the key of dictionary ,with matching values of it with another external list?如何访问字典的键,并将其值与另一个外部列表匹配?
【发布时间】:2021-09-04 06:46:51
【问题描述】:

我想通过检查它的值与另一个列表的元素是否相等来访问字典的键。

def split(word):
    return [char for char in word]

word = '26kk15'

d={'3':['1','2'],'4':['5','6'],'s':['k','l']}
keys=list(d.keys())
l=len(d)
c=0
nl=split(word)
for k in range(0,len(nl)):
    for iu in d.values():
        for j in iu:
            if(j==nl[k]):
                print(keys[c])
        c+=1

我收到列表索引超出范围错误。 如果我删除外部 for 循环,它会给我输出 3 4 s,而我想要 \n3\n4\ns\ns\n3\n4。

【问题讨论】:

  • 仅供参考,您可以使用 list(word) 将字符串转换为列表。
  • 您将c len(nl) * len(keys) 增加倍。由于它比keys 长,因此超出范围。

标签: python python-3.x dictionary


【解决方案1】:

c 超出范围,因为您没有在每次迭代 d.values() 时将其重置为 0

但不需要所有这些额外的列表。使用.items() 对字典的键和值进行迭代,以便在找到匹配值时打印键。

您应该使用in 运算符来测试列表中是否存在某些内容,而不需要另一个嵌套循环。

for letter in word:
    for key, chars in d.items():
        if letter in chars:
            print(key)
            break

【讨论】:

    【解决方案2】:

    在 Python 中,直接遍历集合比获取它的长度、遍历数字索引然后通过 index 再次查找该项目更容易。您甚至可以直接遍历字符串而不将其转换为列表。

    d = {'3': ['1', '2'], '4': ['5', '6'], 's': ['k', 'l']}
    
    word = '26kk15'
    
    for needle in word:
        for key, haystack in d.items():
            # check if the character is in the dict item
            if needle in haystack:
                # if it is, print it and `break` the search loop for given character
                print(key)
                break
    

    【讨论】:

      【解决方案3】:

      以下是使用 python regex 获取所需内容的代码:

      import re
      word = '26kk15'
      
      d={'3':['1','2'],'4':['5','6'],'s':['k','l'], 'b': ['8', '9']}
      for key, values in d.items():
          # Check if elements in 'values' are part of 'word'
          if re.search(r"|".join(values), word):
              print (key)
      

      输出:

      3
      4
      s
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-24
        • 1970-01-01
        • 2022-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-09
        相关资源
        最近更新 更多