Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python-如何计算列表中子字符串的出现次数_Python_Regex_Python 2.7_List_Count - Fatal编程技术网

python-如何计算列表中子字符串的出现次数

python-如何计算列表中子字符串的出现次数,python,regex,python-2.7,list,count,Python,Regex,Python 2.7,List,Count,如果我有这样的清单 list = ['helloA', 'hiA', 'helloB', helloC'] 我想计算该列表中发生的子字符串'hello'的数量 编辑: 实际上,我已经有了一个方法来计算它,如下代码: numb = [x for x,y in enumerate(data['column']) if 'sub-string' in y] print len(numb) 我只是想知道是否有其他方法或更好的方法。 谢谢您可以使用以下方法对每个字符串的布尔检查列表求和: my_lis

如果我有这样的清单

list = ['helloA', 'hiA', 'helloB', helloC']
我想计算该列表中发生的子字符串
'hello'
的数量

编辑

实际上,我已经有了一个方法来计算它,如下代码:

numb = [x for x,y in enumerate(data['column']) if 'sub-string' in y]
print len(numb)
我只是想知道是否有其他方法或更好的方法。
谢谢

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

my_list = ['helloA', 'hiA', 'helloB', 'helloC']
sum('hello' in x for x in my_list)
另外,尽量不要使用
list
作为变量名,因为它是Python中的内置函数/对象。

一个简单的示例

count = 0
string = "hello"
for i in list:
    if string in i:
        count += 1
您可以使用
sum()
中的
运算符来计算子字符串
hello
出现在列表中的次数:

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

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


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

如何计算子字符串?
['hellohello']
会有1个还是2个?
['hel','lo']
是1还是0?您尝试了什么?请阅读@Artyer
['hellohello']
将被计算为1。我的意思是计算列表中包含子字符串的字符串数。@FrancescoMontesano好的,对不起。我将编辑这个问题。Python保留字,也称为关键字,不能用作变量名。您可能想说,
list
是一个内置的-in@Anton,当然可以使用内置类型名作为变量名。然而,仅仅因为Python允许,并不意味着应该这样做。
['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')