Python索引器错误:字符串索引超出范围我做错了什么?

2024-04-24 22:48:43 发布

您现在位置:Python中文网/ 问答频道 /正文

def remove_duplicates(s):
    t=0
    a=s[0]
    while t <= len(s):
        x=0
        while x <= len(a):
            if s[t] != a[x]:
                a+=s[t]
            x+=1
        t+=1
    return a

print(remove_duplicates("zeebra")) #=zebra
print(remove_duplicates("aaaaaa")) #=a

此代码的目标是删除任何字符串中的重复项

相反,我得到的结果是:

line 7, in remove_duplicates if s[t] != a[x]:
IndexError: string index out of range

Tags: 字符串代码目标lenreturnifdefline
2条回答

列表的上界lindex是列表的长度减去1,因为索引从0开始。所以更改:

while t <= len(s):
    x=0
    while x <= len(a):

收件人:

while t < len(s):
    x=0
    while x < len(a):

或者以一种更具python风格的方式,您可以通过简单地将字符串作为序列进行迭代来避免使用索引:

def remove_duplicates(s):
    a = ''
    for t in s:
        if t not in a:
            a += t
    return a

如果您使用的是Python 3.7,其中dict条目是有序的,那么要以最有效的方式进行操作,可以将字符串序列作为dict键加载:

def remove_duplicates(s):
    return ''.join(dict.fromkeys(s))

或者,如果您使用的是早期的Python版本,则可以使用collections.OrderedDict

from collections import OrderedDict
def remove_duplicates(s):
    return ''.join(OrderedDict.fromkeys(s))

你的错误是<=条件。但是,您可以通过使用for循环使代码更具pythonic来摆脱它:

def remove_duplicates(s):
    a=s[0]
    for c in enumerate(s): # c is the character
        if c not in a: # look up c in a
            a += c
    return a

remove_duplicates("zeebra") # 'zebra'
remove_duplicates("aaaaaa") # 'a'

相关问题 更多 >