python - python中字符串的索引函数
问题描述
我正在尝试从头开始实现一个名为say“Function”的函数,该函数计算字母的每个参数z在字符串中顺序出现的次数。
例如, Function('abcbcb', z=2) 应该返回 ab:1, bc:2, cb: 2
或 Function('abcbcb', z=3) 应该返回 abc: 1, bcb: 2, cbc: 1
我曾尝试使用循环和 python 字符串方法,但我还不能编写一个有效的方法。
谢谢!
解决方案
首先让我们给这个函数起个名字,因为这个名字很容易混淆。我会称之为时间。
iterable[n:k]
将返回从索引 n(包括)到索引 k(不包括)的迭代。
这是一个带有解释的代码:
def times(str, z):
dict ={} # we create an empty dict
for i in range(len(str)-z+1): #we loop over the string a number of times depending on z so we can check all z length paramters
if str[i:i+z] in dict.keys(): #if the part of the string is in the keys of the dictionary then we add one
dict[str[i:i+z]] += 1
else:
dict[str[i:i+z]] = 1 # if it wasn't we set it to one
return dict
times('abcbcb',3)
推荐阅读
- mongoose - 不允许在 Mongoose 和 Node JS 中添加相同级别的主题
- matlab - for 循环仅显示迭代的最后一个值
- python - 这使用什么算法进行人脸识别?
- android - 找不到符号返回 DaggerApplication_HiltComponents_SingletonC.builder()
- chart.js - 在雷达图中隐藏数据集的数据?
- asp.net-core - 创建用于过滤名称、价格和可用性的端点
- xml - Python 2.6.6:无法从当前元素的直接子元素中提取文本
- python - 如何在 python 中向生成器发送数据
- javascript - 相对于世界时钟,每 15 分钟后将每个 div 的位置顺时针替换 1 步
- entity-framework - 在 EFCore 中关闭全局过滤器警告