【问题标题】:Comparing to dictionaries in Python与 Python 中的字典比较
【发布时间】:2021-08-25 16:45:21
【问题描述】:

我有一个函数,它接受一个字符串来计算单个字符并将字符连同它出现的时间量一起放入一个字符串中。例如:

isanagram("surfer")

返回

w1 = {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 1, 'f': 1, 'g': 0, 'h': 0, 'i': 0, 'j': 0, 'k': 0, 'l': 0, 'm': 0, 'n': 0, 'o': 0, 'p': 0, 'q': 0, 'r': 2, 's': 1, 't': 0, 'u': 1, 'v': 0, 'w': 0, 'x': 0, 'y': 0, 'z': 0}

虽然当我将此函数与两个不同的参数进行比较时,打印语句输出 True 而不是 False,这显然应该是。有没有人可以看看。这是我的代码:

alphabetlist = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    alphabetdict = {}
    newalphadict = {}    
              
    def isanagram(aword):
        for i in alphabetlist:
            count = word.count(i) 
            alphabetdict[i] = count
            
        return alphabetdict
    
     print(isanagram("computer") == isanagram("science")) #outputting True. Should be outputting False.

【问题讨论】:

  • isanagram()aword 作为参数,但在函数中您使用word
  • 你不断地添加到同一个字典对象中......
  • aside:python 有一个 Counter 对象:from collections import Counter; c = Counter("computer")

标签: python python-3.x function dictionary


【解决方案1】:

您的代码存在一些问题。这是一个更好的版本:

from collections import Counter

def is_anagram(word1, word2):    

    c1 = Counter(word1)
    c2 = Counter(word2)
    return c1 == c2

is_anagram("computer", "science") # False

这解决了您当前代码的以下问题:

  • newalphadictalphabetdict 位于您的函数之外,因此每次调用 isanagram 时都会向它们添加字母(一个错误)
  • is_anagram 比较两个词。它可能应该以两个词作为参数(仅此而已)。
  • aword != word
  • 您不必预先填充字典。您可以使用一些 try/accept 逻辑和 dict 来完成此操作,或者使用 defaultdict,但 Counter 已经存在,所以让我们使用它。

【讨论】:

  • 为什么会有bool() 的演员表? c1 == c2 已经返回一个布尔值。
  • 为了清楚起见,不需要
  • 我认为它会降低清晰度。我看着它,想象Counter 一定是在用__eq__ 做一些奇怪的事情。
【解决方案2】:
alphabetlist = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
        
def isanagram(word=''):
    alphabetdict = {}
    for i in alphabetlist:
        count = word.count(i) 
        alphabetdict[i] = count
    
    return alphabetdict

print(isanagram("computer") == isanagram("science")) #-> False

【讨论】:

  • 虽然只有代码的答案可能会回答这个问题,但您可以通过为您的代码提供上下文、此代码工作的原因以及一些文档参考以供进一步阅读,从而显着提高您的答案质量.来自How to Answer“简洁是可以接受的,但更全面的解释更好。”
猜你喜欢
  • 1970-01-01
  • 2019-06-15
  • 1970-01-01
  • 1970-01-01
  • 2010-09-30
  • 1970-01-01
  • 2012-04-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多