我的目标是获取一个字符串并找到每个字母的第一次出现并将其附加到一个字符串中。您将从原始字符串中删除这些字母并重复,直到原始字符串为空。例如,“aabdc”应返回“abcad”。为此,我将字符串拆分为一个列表,并通过它检查每个字母。但是,我不断收到索引超出范围错误,因为我的 for i in range(len(string)) 在我从字符串中删除某些字符后不断变化。我该如何解决这个问题?
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
def split(word):
return list(word)
def order(s):
output = ""
x = 0
s = split(s)
for i in range(len(s)):
if alphabet[x] not in s:
x += 1
if alphabet[x] == s[i]:
output += s[i]
print(output)
s.remove(s[i])
print(s)
x += 1
return(output)
答案 0 :(得分:0)
您在迭代时删除列表项,因此其长度减少。您应该使用列表的副本来搜索字母。
只需为 for 循环(即 s.copy()
)创建列表的副本,然后在迭代期间删除 s 的项目。
答案 1 :(得分:0)
当您删除列表中的项目时,您只需要减少名为“i”的变量以使其保持有序。 检查以下代码:
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
def split(word):
return list(word)
def order(s):
output = ""
x = 0
s = split(s)
i = 0
while i < len(s):
if alphabet[x] not in s:
x += 1
if alphabet[x] == s[i]:
output += s[i]
print(output)
s.remove(s[i])
i = i - 1
print(s)
x += 1
return(output)