简体   繁体   English

计算字符串中项目列表的出现?

[英]Count the occurence of a list of items in a string?

How will I be able to count the number of time a list of items are repeated in a string. 如何计算一个项目列表在一个字符串中重复的次数。 For example how can I search through string and check the number of times this list has been repeated in string? 例如,如何搜索字符串并检查此列表在字符串中重复的次数?

list = ('+','-','*','/')
string = "33+33-33*33/33"

Firstly, don't use a name like list , it masks the built-in name list [See: Built-in Methods ] and that can lead to some subtle bugs. 首先,不要使用诸如list类的名称,它会掩盖内置名称list [请参阅: 内置方法 ],这可能会导致一些细微的错误。

After that, there's ways to do this. 在那之后,有一些方法可以做到这一点。 The crucial thing to have in mind is that objects like strings come along with a plethora of methods [See: String Methods ] that act on them. 要记住的关键是,像字符串之类的对象会伴随着许多作用于它们的方法 [请参见: 字符串方法 ]。 One of these methods is str.count(sub) which counts the number of times sub occurs in your string. 这些方法之一是str.count(sub) ,它计算sub在字符串中出现的次数。

So, creating a count for every element in lst could be done by using a for loop: 因此,可以使用for循环for lst每个元素创建一个计数:

lst = ('+','-','*','/')
string = "33+33-33*33/33"
for i in lst:
    print("Item ", i, " occured", str(string.count(i)), "times")

str(string.count(i)) transforms the integer result of string.count to an str object so it can be printed by print . str(string.count(i))string.count的整数结果转换为str对象,以便可以通过print

This prints out: 打印输出:

Item  +  occured 1 times
Item  -  occured 1 times
Item  *  occured 1 times
Item  /  occured 1 times

After getting more accustomed to Python you could use a comprehension to create a list of the results and supply them to print : 逐渐熟悉Python之后,您可以使用一种理解来创建结果列表并将其提供给print

print(*["Item {} occured {} times".format(x, string.count(x)) for x in lst], sep='\n')

which prints a similar result. 打印出类似的结果。

Finally, make sure you read the Tutorial available on the Python documentation website, it'll help you get acquainted with the language. 最后,确保您阅读了 Python文档网站上的Tutorial ,它可以帮助您熟悉该语言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM