如何在python中修复'IndexError:列表索引超出范围'?

时间:2019-04-21 11:50:40

标签: python list indexing

我已经10年级了,真的很不擅长编码。基本上,我正在尝试制作一个非常简单的演进模拟器,到目前为止它一直运行良好,但是在使用列表定义变量时遇到了该错误。我附上了完整的代码。

#************************#
#*  Jadday's Amazing    *#
#* Evolution Simulator  *#
#************************#

import random

print("The Evolution Starts Here")

numcs = 100

def generation1():
    global numcs
    profiles = []
    maxscore = 0
    minscore = 100
    x = 0
    for i in range(0,numcs):
        a = random.randint(0,75)
        b = random.randint(a,100)
        score = random.randint(a,b)
        name = [a,b]
        x = str(x)
        x = int(x)
        x = x + 1

        if score > maxscore:
            maxscore = score
            score = str(score)
            best = score
            score = int(score)

        if score < minscore:
            minscore = score
            score = str(score)
            worst = score
            score = int(score)

        score = str(score)
        profile = score
        score = int(score)
        profiles.append(score)
        profiles = [int(x) for x in profiles]
        profiles.sort()
        print(profile)
    print("")
    print("")
    print("The best was:")
    print(best)
    print("")
    print("The worst was:")
    print(worst)

    numcs = numcs // 2

    templength = len(profiles)
    length = templength // 2

    for x in range(0,length):
        del profiles[0]

    print("")
    print(profiles)



def generation():
    global numcs
    profiles = []
    maxscore = 0
    minscore = 100
    x = 0
    for i in range(0,numcs):
        a = profiles[i]
        a = a / 2
        b = profiles[i]
        b = b * 2
        score = random.randint(a,b)
        name = [a,b]
        x = str(x)
        x = int(x)
        x = x + 1

        if score > maxscore:
            maxscore = score
            score = str(score)
            best = score
            score = int(score)

        if score < minscore:
            minscore = score
            score = str(score)
            worst = score
            score = int(score)

        score = str(score)
        profile = score
        score = int(score)
        profiles.append(score)
        profiles = [int(x) for x in profiles]
        profiles.sort()
        print(profile)
    print("")
    print("")
    print("The best was:")
    print(best)
    print("")
    print("The worst was:")
    print(worst)

    numcs = numcs // 2

    templength = len(profiles)
    length = templength // 2

    for x in range(0,length):
        del profiles[0]

    print("")
    print(profiles)




generation1()
for x in range(0,6):
    generation()
    numcs = numcs // 2

定义“世代”时,错误出现在“ a = profile [i]”行中。 我很可能在做模拟器时效率很低,但是我试图使其更简单。 如果有人知道如何解决这个问题,我将不胜感激。 谢谢

1 个答案:

答案 0 :(得分:0)

在功能generation1中,您的profiles = []为空列表。在下一行中,尝试使用profiles[i],其中i的范围是0到100。