[英]How to count the number of times a certain pattern in a sublist occurs within a list and then append that count to the sublist?
[英]How to count the number of times something occurs inside a certain string?
在python中,我记得有一个函数可以做到这一点。
。计数?
“大棕狐狸是棕”棕= 2。
为什么不先阅读文档,这很简单:
>>> "The big brown fox is brown".count("brown")
2
如果您是Python初学者,则值得学习的一件事是如何使用交互式模式来帮助解决此问题。 首先要学习的是dir
函数 ,它将告诉您对象的属性。
>>> mystring = "The big brown fox is brown"
>>> dir(mystring)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__
ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__g
t__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__
', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '
__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode',
'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdi
git', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lst
rip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit'
, 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', '
translate', 'upper', 'zfill']
请记住,在Python中,方法也是属性。 因此,现在他使用help
功能来查询一种看似有希望的方法:
>>> help(mystring.count)
Help on built-in function count:
count(...)
S.count(sub[, start[, end]]) -> int
Return the number of non-overlapping occurrences of substring sub in
string S[start:end]. Optional arguments start and end are interpreted
as in slice notation.
这将显示方法的文档字符串 -一些帮助文本,您也应该养成放入自己的方法的习惯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.