簡體   English   中英

字符串中的字母索引 - python 2.7

[英]index of a letter in string - python 2.7

* 我正在編輯這個問題因為我有一些錯誤,請再讀一遍 * *

我正在構建一個用單詞構建字典的函數,例如:

{'b': ['b', 'bi', 'bir', 'birt', 'birth', 'birthd', 'birthda', 'birthday'], 'bi': ['bi', 'bir', 'birt', 'birth', 'birthd', 'birthda', 'birthday'], 'birt': ['birt', 'birth', 'birthd', 'birthda', 'birthday'], 'birthda': ['birthda', 'birthday'], 'birthday': ['birthday'], 'birth': ['birth', 'birthd', 'birthda', 'birthday'], 'birthd': ['birthd', 'birthda', 'birthday'], 'bir': ['bir', 'birt', 'birth', 'birthd', 'birthda', 'birthday']}

這就是它的樣子:

def add_prefixs(word, prefix_dict):
lst=[]
for letter in word:
    n=word.index(letter)
    if n==0:
        lst.append(word[0])
    else:
        lst.append(word[0:n])
lst.append(word)
lst.remove(lst[0])
for elem in lst:
    b=lst.index(elem)
    prefix_dict[elem]=lst[b:]
return prefix_dict

它適用於像“生日”這樣的單詞,但是當我有一個重復的字母時,我有一個問題......例如,“你好”。

{'h': ['h', 'he', 'he', 'hell', 'hello'], 'hell': ['hell', 'hello'], 'hello': ['hello'], 'he': ['he', 'he', 'hell', 'hello']}

我知道這是因為索引(python選擇字母第一次出現的索引)但我不知道如何解決它。 是的,這是我的作業,我真的想向你們學習:)

謝謝!

使用enumerate

for n, letter in enumerate(word):
    if n==0 or n==1:
        continue
    else:
        lst.append(word[0:n])
a = 'birthday'
[a[:i] for i in range(2,len(a)+1)]

['bi', 'bir', 'birt', 'birth', 'birthd', 'birthda', 'birthday']

所以你可以用簡單的方式替換你的功能:

prefix_dict[word] = [word[:i] for i in range(2,len(word)+1)]

假設變量a是一個簡單的字符串(例如,“birthday”,“hello”),您可以使用:

for i in range(1,len(a)):
    print a[0:i+1]
def add_prefixs(word, prefix_dict):
    prefix_dict[word] = [ word[:n+1] for n in range(1, len(word)) ]

更好的是:

def get_words(word):
    return [ word[:n+1] for n in range(1, len(word)) ]
prefix_dict[word] = get_words(word)

所以你保持你的功能“純粹”。

暫無
暫無

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

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