Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.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_Function - Fatal编程技术网

python中字符串的索引函数

python中字符串的索引函数,python,function,Python,Function,我试图从头开始实现一个名为say“function”的函数,该函数计算每个字母参数z在字符串中顺序出现的次数 例如,函数('abcbcb',z=2) 应该返回ab:1,bc:2,cb:2 or函数('abcbcb',z=3)应返回 abc:1,bcb:2,cbc:1 我已经尝试过使用循环和python字符串方法,但我还不能编写一个有效的方法 谢谢大家! 首先,让我们将函数另起一个名字,因为这个名字令人困惑。我会叫它倍 iterable[n:k]将把iterable从索引n(包含)返回到索引k(独

我试图从头开始实现一个名为say“function”的函数,该函数计算每个字母参数z在字符串中顺序出现的次数

例如,函数('abcbcb',z=2) 应该返回ab:1,bc:2,cb:2

or函数('abcbcb',z=3)应返回 abc:1,bcb:2,cbc:1

我已经尝试过使用循环和python字符串方法,但我还不能编写一个有效的方法


谢谢大家!

首先,让我们将函数另起一个名字,因为这个名字令人困惑。我会叫它倍
iterable[n:k]
将把iterable从索引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)

对不起,英语是我的第二语言。

这需要循环和字典。祝你好运