簡體   English   中英

為 python 中的字符串索引 function

[英]Indexing function for a string in python

我正在嘗試從頭開始實現一個名為“功能”的 function,它計算每個字母參數 z 在字符串中順序出現的次數。

例如, Function('abcbcb', z=2) 應該返回 ab:1, bc:2, cb: 2

或 Function('abcbcb', z=3) 應該返回 abc: 1, bcb: 2, cbc: 1

我嘗試過使用循環和 python 字符串方法,但我還不能編寫一個有效的方法。

謝謝!

首先讓我們將 function 稱為另一個名稱,因為這個名稱令人困惑。 我會稱之為時間。
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)

對不起英語,它對我來說是第二語言。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM