【问题标题】:How do I create a dictionary from a string returning the number of characters [duplicate]如何从返回字符数的字符串创建字典[重复]
【发布时间】:2015-02-24 07:17:58
【问题描述】:

我希望将'ddxxx' 等字符串作为('d': 2, 'x': 3) 返回。到目前为止我已经尝试过

result = {}
for i in s:
    if i in s:
        result[i] += 1
    else:
        result[i] = 1
return result   

其中s 是字符串,但我不断收到KeyError。例如。如果我将s 设置为'hello',则返回的错误是:

result[i] += 1
KeyError: 'h'

【问题讨论】:

    标签: python string dictionary


    【解决方案1】:

    如果您不想使用collections 模块,这里有一个简单的方法:

    >>> st = 'ddxxx'
    >>> {i:st.count(i) for i in set(st)}
    {'x': 3, 'd': 2}
    

    【讨论】:

      【解决方案2】:

      使用collections.Counter 是明智的解决方案。但是如果您确实想重新发明轮子,可以使用dict.get() 方法,它允许您为丢失的键提供默认值:

      s = 'hello'
      
      result = {}
      for c in s:
          result[c] = result.get(c, 0) + 1
      
      print result
      

      输出

      {'h': 1, 'e': 1, 'l': 2, 'o': 1}
      

      【讨论】:

        【解决方案3】:

        您可以使用collections.Counter 轻松解决此问题。 Counter 是用于计算事物的标准 dict 的子类型。当您尝试增加以前没有出现在字典中的内容时,它会自动确保创建索引,因此您无需自己检查。

        您还可以将任何可迭代对象传递给构造函数,以使其自动计算该可迭代对象中项目的出现次数。由于字符串是可迭代的字符,因此您只需将字符串传递给它即可计算所有字符:

        >>> import collections
        >>> s = 'ddxxx'
        >>> result = collections.Counter(s)
        >>> result
        Counter({'x': 3, 'd': 2})
        >>> result['x']
        3
        >>> result['d']
        2
        

        当然,手动方式也可以,您的代码几乎可以正常工作。由于您得到KeyError,因此您正在尝试访问字典中不存在的键。当您碰巧遇到一个您以前没有计算过的新角色时,就会发生这种情况。您已经尝试使用 if i in s 检查来处理该问题,但您正在检查错误的收容措施。 s 是您的字符串,并且由于您正在迭代字符串的字符 ii in s 将始终为真。相反,您要检查的是i 是否已经作为字典result 中的键存在。因为如果没有,您将其添加为计数为1 的新键:

        if i in result:
            result[i] += 1
        else:
            result[i] = 1
        

        【讨论】:

          【解决方案4】:

          问题在于您的第二个条件。 if i in s 正在检查字符串本身而不是字典中的字符。它应该是 if i in result.keys() 或 Neil mentioned 它可以只是 if i in result

          例子:

          def fun(s):
              result = {}
              for i in s:
                  if i in result:
                      result[i] += 1
                  else:
                      result[i] = 1
              return result   
          
          print (fun('hello'))
          

          这会打印出来

          {'h': 1, 'e': 1, 'l': 2, 'o': 1}
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-12-05
            • 1970-01-01
            • 1970-01-01
            • 2021-12-01
            • 1970-01-01
            • 1970-01-01
            • 2016-12-25
            相关资源
            最近更新 更多