【问题标题】:Python strip and Counter for top 3 alphabets前 3 个字母的 Python 条和计数器
【发布时间】:2017-08-10 10:27:23
【问题描述】:

输出应该是给定输入的前 3 个字母,但即使在输入上使用了 strip 函数后,我也无法删除空格。 代码:

    from collections import Counter
    insider = input("Enter the input you wanna enter : ")
    actual = insider.strip()
    count = Counter()
    for i in actual:
        count[i]+=1
    print(count.most_common(3))

输出:

    Enter the input you wanna enter : is this the ral life or is it just fantasy
    [(' ', 9), ('i', 5), ('s', 5)]

【问题讨论】:

    标签: python python-3.x collections counter strip


    【解决方案1】:

    strip 只会删除前导和尾随空格。

    您可以使用替换删除空格:

    actual = insider.replace(' ', '')
    

    【讨论】:

      【解决方案2】:

      使用("").join(insider.split()) 代替insider.strip()split 方法将从字符串中删除空格并将其转换为列表,您可以使用("").join(str) 将其转换为字符串。

      你的代码现在变成了

      from collections import Counter
      insider = input("Enter the input you wanna enter : ")
      actual = ("").join(insider.split())
      count = Counter()
      for i in actual:
          count[i]+=1
      print(count.most_common(3))
      

      给了

      Enter the input you wanna enter : is this the ral life or is it just fantasy
      [('i', 5), ('s', 5), ('t', 5)]
      

      【讨论】:

        【解决方案3】:

        您可以使用''.join(s.split()) 删除空格字符。然后直接从中构造counter。

        from collections import Counter
        
        s = input("Enter the input you wanna enter : ")
        
        s = ''.join(s.split())
        
        print(counter = Counter(s))
        
        counter.most_common(3)
        

        【讨论】:

          【解决方案4】:

          感谢您的回答,我猜代码不能比这更短?

          from collections import Counter
          insider = input("Enter the input you wanna enter : ").lower()
          actual = ''.join(insider.split())
          print(Counter(actual).most_common(3))
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2021-12-19
            • 1970-01-01
            • 2011-01-15
            • 1970-01-01
            • 2021-04-29
            • 2017-12-29
            • 2013-04-22
            相关资源
            最近更新 更多