Python IndexError:字符串索引超出范围-我在做什么错?

时间:2018-10-18 03:12: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

2 个答案:

答案 0 :(得分: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键加载:

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))

答案 1 :(得分:0)

您的错误是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' 条件。但是,您可以通过使用for循环使代码更具pythonic来摆脱它:

public class People {

    private Student[10];
    private Teacher[10];

    public void setStudentArray(Student, index) {
        Student[index] = Student;
    }

    public void setTeacherArray(Teacher, index) {
        Teacher[index] = Teacher;
    }
}

public class Student extends People {
    String name;
    int StudentID;
    public String getName() {
        return name;
    }
}

public class Teacher extends People {
    String name ;
    int Teacher ID;
    public String getName() {
        return name;
    }
}
public class Main {
    People p = new People();

    public void main (String[] args) {
        Student s = new Student("default-name" , 1);
        p.setStudentArray(s, 0);

        Teacher t = new Teacher("default-name", 1);
        p.setTeacherArray(t, 0);

        outputName(p.getStudentArray, 0);
        outputName(p.getTeacherArray, 0)
    }

    //THIS IS WHERE I AM STRUGGLING I dont know how to pass teachers or students array to it.
    //I want the Object[] parameter to accept both Student[] and Teacher[]

    public void outputName(Object[], index) {
        System.out.println(Object[index].getName);  
    }   
}