【问题标题】:python - How to count the number of occurances of sub-string in a listpython - 如何计算列表中子字符串的出现次数
【发布时间】:2017-07-01 15:12:54
【问题描述】:

如果我有一个类似的列表

list = ['helloA', 'hiA', 'helloB', helloC']

我想计算该列表中出现的子字符串 'hello' 的数量。

编辑

其实我已经有办法像下面这段代码那样计算它了:

numb = [x for x,y in enumerate(data['column']) if 'sub-string' in y]
print len(numb)

我只是想知道是否有其他方法或更好的方法来做到这一点。 谢谢

【问题讨论】:

  • 你是如何计算子串的? ['hellohello'] 会有 1 还是 2? ['hel', 'lo'] 是 1 还是 0?
  • @Artyer ['hellohello'] 将被计为 1。我的意思是计算列表中包含子字符串的字符串数。
  • @FrancescoMontesano 好的,对不起。我将编辑问题。

标签: python regex python-2.7 list count


【解决方案1】:
['hello' in x for x in list].count(True)

sum(['hello' in x for x in list ])

len([1 for x in list if 'hello' in x])

''.join(list).count('hello')

注意:如果您的某些字符串多次包含“hello”子字符串,则最后一种方法可能会提供与前三种方法不同的计数 - 请参阅@Artyer 对您原始问题的评论。

另外,避免调用列表名称“list”(Python 中的内置类型)。

【讨论】:

    【解决方案2】:

    一个简单的例子

    count = 0
    string = "hello"
    for i in list:
        if string in i:
            count += 1
    

    【讨论】:

      【解决方案3】:

      您可以使用sum()in 运算符将带有子字符串hello 的字符串出现在列表中的次数相加:

      >>> lst = ['helloA', 'hiA', 'helloB', 'helloC']
      >>> sum(string.count('hello') for string in lst)
      3
      >>> 
      

      【讨论】:

        【解决方案4】:

        您可以使用以下方法对每个字符串的布尔检查列表求和:

        my_list = ['helloA', 'hiA', 'helloB', 'helloC']
        sum('hello' in x for x in my_list)
        

        另外,尽量不要使用 list 作为变量名,因为它是 Python 中的内置函数/对象。

        【讨论】:

        • Python 保留字,又名关键字,不能用作变量名。你可能想说list 是内置的
        • @Anton,当然可以使用内置类型名称作为变量名称。然而,仅仅因为 Python 允许它——并不意味着应该这样做。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-22
        • 1970-01-01
        • 1970-01-01
        • 2020-02-21
        • 2012-02-12
        相关资源
        最近更新 更多