gpt4 book ai didi

python - 在重复字母上使用 `.index()`

转载 作者:太空宇宙 更新时间:2023-11-04 09:12:13 25 4
gpt4 key购买 nike

我正在构建一个用单词构建字典的函数,例如:

{'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选择字母第一次出现的索引)但我不知道如何解决它。是的,这是我的作业,我真的很想向你们学习 :)

最佳答案

你已经遍历了这个词;而不是使用 .index() 保留一个计数器。 Python 使这对你来说非常容易;使用 enumerate() 函数:

for n, letter in enumerate(word):
if n==0:
lst.append(word[0])
else:
lst.append(word[0:n])

不过,现在您不再使用 letter 变量,所以只用 range(len(word) 代替:

for n in range(len(word)):
if n==0:
lst.append(word[0])
else:
lst.append(word[0:n])

我们可以将其简化为列表理解:

lst = [word[0:max(n, 1)] for n in range(len(word))]

注意那里的 max();我们不测试 n 是否为 0,而是为切片设置最小值 1

由于您随后再次删除第一个条目(因为它与第二个结果相同)并且您添加了完整的单词,只需将 1 添加到n 计数器改为:

lst = [word[0:n+1] for n in range(len(word))]

函数的后半部分可以有效地使用enumerate()函数,而不是.index():

for b, elem in enumerate(lst):
prefix_dict[elem]=lst[b:]

现在你的函数简单多了;请注意,无需返回 prefix_dict,因为您正在就地操作它:

def add_prefixs(word, prefix_dict):
lst = [word[0:n+1] for n in range(len(word))]
for b, elem in enumerate(lst):
prefix_dict[elem]=lst[b:]

关于python - 在重复字母上使用 `.index()`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13588943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com