简体   繁体   English

为 python 中的字符串索引 function

[英]Indexing function for a string in python

I am trying to implement a function called say "Function" from scratch that counts how many times each parameter z of letters occurs sequentially in a string.我正在尝试从头开始实现一个名为“功能”的 function,它计算每个字母参数 z 在字符串中顺序出现的次数。

For example, Function('abcbcb', z=2) should return ab:1, bc:2, cb: 2例如, Function('abcbcb', z=2) 应该返回 ab:1, bc:2, cb: 2

or Function('abcbcb', z=3) should return abc: 1, bcb: 2, cbc: 1或 Function('abcbcb', z=3) 应该返回 abc: 1, bcb: 2, cbc: 1

I have tried using loops and python string methods but I have not been able to write a working one yet.我尝试过使用循环和 python 字符串方法,但我还不能编写一个有效的方法。

Thank you!谢谢!

First let's call the function another name because this one is confusing.首先让我们将 function 称为另一个名称,因为这个名称令人困惑。 I'll call it times.我会称之为时间。
iterable[n:k] will return the iterable from index n (inclusive) to index k(exclusive). iterable[n:k]将返回从索引 n(包括)到索引 k(不包括)的迭代。
here is a code with explanations:这是一个带有解释的代码:

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)

Sorry for the english, it is a second language for me.对不起英语,它对我来说是第二语言。

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

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