【问题标题】:Count multiple characters in a string separately分别计算字符串中的多个字符
【发布时间】:2017-03-23 23:19:51
【问题描述】:

我的老师让我编写一个函数来使用另一个字符串字母来计算一个字符串的出现次数。比如:

>>>problem3("all is quiet on the western front", "tqe")
>>>["t=4", "q=1", "e=4"]

但是我只能做到:

>>>problem3("all is quiet on the western front", "tqe")
>>>[4, 1, 4]

这是我的代码:

def problem3(myString, charString):
    return [myString.count(x) for x in (charString)]

我如何获得这种格式的 ["t=4", "q=1", "e=4"]?

【问题讨论】:

    标签: string list python-3.x letter


    【解决方案1】:

    所以你只是被要求非常具体地格式化它并且你很接近,只需要格式化结果:

    def problem3(myString, charString):
        return ['{}={}'.format(x, myString.count(x)) for x in charString]
    
    >>> problem3("all is quiet on the western front", "tqe")
    ['t=4', 'q=1', 'e=4']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 2016-07-25
      • 2015-12-01
      • 2022-07-08
      • 2015-07-08
      • 1970-01-01
      • 2019-09-14
      相关资源
      最近更新 更多