【问题标题】:compare key and values at corresponding index in python比较python中相应索引处的键和值
【发布时间】:2018-09-25 13:44:27
【问题描述】:

python.key中有字典,比较值的拼写,如果错误大于等于2则打印不正确

input={"他们的":"thuyr"}

输出=不正确(因为 t=t,h=h 但 e!=u,i!=y)。

我的问题是我无法比较 t==t,h==h,e==u,i==y。 下面的代码显示计数值为 22,但计数值必须为 2,因为只有两个单词与其不匹配

def find_correct(words_dict):
    count=0
    for key,value in words_dict.items():
        for val in value:
            for ky in key:
                if(val!=ky):
                    count+=1  
    return count     

print(find_correct({"their":"thuor"})) 

【问题讨论】:

    标签: python dictionary match key-value


    【解决方案1】:

    这是因为您使用的是嵌套循环。它将“their”中“t”的每个字母与“thuor”中的每5个字母进行比较。相反,只需使用这样的单个循环:

    def find_correct(words_dict):
    count=0
    for key,value in words_dict.items():
        for val, ky in zip(value, key):
            if(val!=ky):
                count+=1  
    return count     
    

    【讨论】:

      猜你喜欢
      • 2015-04-07
      • 1970-01-01
      • 2020-01-05
      • 2012-07-10
      • 1970-01-01
      • 2020-04-10
      • 2022-11-29
      • 2014-03-13
      • 2019-07-07
      相关资源
      最近更新 更多