我想要一个在字符串内部查找子字符串的列表,并接收子字符串在该字符串中出现的次数。
list = ['one', 'two', 'three']
str = "one one two four five six"
count = str.count(list)
所以在这个例子中,count应该是3。但是,由于某种原因,.count()无法从列表中读取字符串,所以我不知道如何解决这个问题。
最佳答案
一种方法是将 sum
与生成器表达式结合使用,并利用 set
进行 O(1) 查找。 str.split()
将字符串拆分为一个列表,并以空格分隔。
str_set = {'one', 'two', 'three'}
x = 'one one two four five six'
count = sum(i in str_set for i in x.split())
print(count) # 3
其工作原理是 bool
是 int
的子类,因此我们可以对 True
元素进行求和,就好像它们是整数一样。
请注意,您有一个列表和字符串,不涉及元组。此外,不要在类之后命名变量(例如 list
、str
、set
)。
关于python - 计算字符串内列表中的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50532977/