【问题标题】:How can i print number of times each alphabet occurs in the string?如何打印字符串中每个字母出现的次数?
【发布时间】:2021-01-31 14:05:04
【问题描述】:

好吧,我试图在 python 中为等图编写代码作为我的任务,所以我被困在这里
我考虑过以下事情
1.所有输入的字都是小号
2. 只包含字母,没有特殊字符或数字

word =input("enter the word ")
list_of_alphabets = list(word)
no_of_alphabets = len(list_of_alphabets)
for i in range(no_of_alphabets):
  number = list_of_alphabets.count()
  print (number)

我现在卡在这里了,我希望 for 循环检查每个字母是否出现一次,并打印每个字母出现的次数。如果不是,那么它应该打印 not an isogram ,如果是则打印 isogram 。另外,如果此代码有其他方法,我也希望
PS。请不要向我推荐 geeksforgeek 的代码,因为我已经看过了

【问题讨论】:

    标签: python python-3.x list


    【解决方案1】:

    只需使用collections.Counter:

    >>> c = Counter('gallahad')
    >>> c
    Counter({'a': 3, 'l': 2, 'g': 1, 'h': 1, 'd': 1})
    

    如果您需要检查字符串中有多少特定符号,请使用count 方法:

    >>> 'gallahad'.count("a")
    3
    

    【讨论】:

      【解决方案2】:

      更正您发布的代码。

      对代码的更改

      word = input("enter the word ")
      #list_of_alphabets = list(word)               -- not needed
      #no_of_alphabets = len(list_of_alphabets)     -- not needed
      #for i in range(no_of_alphabets):             --  change to following
      for letter in word:                          # loop through each letter in word
        number = word.count(letter)      
        if number > 1:
          print("Not a isogram")
          break
      else:
          # Will enter here only if did not encounter break in above for loop
          print("Is a isogram")
      

      清理完上面我们有

      word = input("enter the word ")
      for letter in word:
        number = word.count(letter)      
        if number > 1:
          print("Not a isogram")
          break
      else:
          print("Is a isogram")
      

      Daniel Hao 建议的替代方案

      使用 Python sets

      word = input("enter the word ")
      if len(word) == len(set(word)):
          print("Is a isogram")
      else:
          print("Not a isogram")
      

      【讨论】:

      • 或者更简单 - 只需使用 'set' 来检查前后的 len ...
      • @DanielHao——另一个不错的选择,所以添加它作为替代。
      • 酷。然后它可以作为一个简单的函数 - is_isogram(word) 作为一行。谢谢。
      【解决方案3】:

      根据@dukkee 的意见。你也可以试试这个

      value ="gallahad"
      print({i:value.count(i) for i in value})
      

      【讨论】:

        猜你喜欢
        • 2020-03-29
        • 2013-07-20
        • 2016-01-23
        • 1970-01-01
        • 1970-01-01
        • 2017-04-04
        • 2020-07-23
        • 1970-01-01
        • 2022-10-09
        相关资源
        最近更新 更多