【问题标题】:using Python reduce Count the number of occurrence of character in string使用 Python reduce 计算字符串中字符的出现次数
【发布时间】:2018-03-21 04:09:30
【问题描述】:

如何使用python reduce函数查找给定字符串“string”中存在的“char”数量?

我刚刚了解 reduce。它只会返回一个元素。所以我认为应该有办法使用 reduce 来完成这项工作。

目前没有找到。

示例:

char:'s'
inputstring:'assntcs'

output(number of occurrence of s in 'assntcs'):-3

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    肯定有更好的方法来做到这一点,但如果你真的想使用 reduce,你可以使用以下方法:

    >>> from functools import reduce
    >>> reduce(lambda x, y: x + (1 if y == 's' else 0), 'assntcs', 0)
    3
    

    如果它们是您要查找的字符,这只是计算该字符串中的元素,在本例中为s

    同样,这过于复杂。你可以简单地使用count():

    >>> 'assntcs'.count('s')
    3
    

    【讨论】:

    • 谢谢你..这很有帮助。刚刚在学习reduce的使用。
    猜你喜欢
    • 1970-01-01
    • 2014-04-24
    • 1970-01-01
    • 2014-06-10
    • 2012-12-18
    • 2020-02-21
    • 2012-02-12
    相关资源
    最近更新 更多