【问题标题】:Errors with outputting a list输出列表的错误
【发布时间】:2017-05-12 04:57:54
【问题描述】:

我在输出我拥有的一堆函数的结果时遇到问题。非常感谢任何信息,因为我已经被困了好几个小时了。

错误:

minNum = theArray[0]
IndexError: list index out of range

期望的输出:

The original array was:
[22, 49, 80, 4, 53, 31, 6, 30, 61, 87]
The maximum value is: 87
The minimum value is: 4
The total value is: 423
The average value is: 42.3
The sorted array is:
[4, 6, 22, 30, 31, 49, 53, 61, 80, 87]

功能: randIntArray - 填充随机整数数组(用于测试)。 getInt(prompt) - 尝试从用户获取整数 10x。 getData() - 使用 getInt 执行循环 10 次,将整数存储到数组 (userIntList) 中。 swap - 列表的交换例程。 sortArray - 使用交换例程进行排序。 displayArray - 打印数组。 maxValue - 查找列表中的最大值(不使用 python 内置函数)。 minValue - 查找列表中的最小值(不使用 python 内置函数)。 aveValue - 查找列表中的 ave #(不使用 python 内置函数)。 totalValue - 查找列表中整数的总数(不使用 python 内置函数) dataOut(theArray) - 打印上面列出的值。 processInput(theArray) - 使用 dataOut,排序,并以未排序和排序的形式提示列表。 unitTest - 使用随机整数函数进行测试并打印结果。

import random

def randIntArray():
    randomList = []
    randomList = random.sample(range(1, 101), 10)
    return randomList

def getInt(prompt):
    # Function to call when asking for the A and B values later.
    try:
        x = input(prompt)
        y = int(x)
        return y  
    except:
        print("That was not an integer. Please enter an integer. ")


def getData():
    userIntList = []
    for i in range(10):
        userNum = getInt("Please enter value number : ")
        userIntList.append(userNum)
    return userIntList


def swap(a, j, k):
    temp1 = a[j]
    a[j] = a[k]
    a[k] = temp1

def sortArray(a):
    for i in range(len(a)):
        for k in range(len(a) - 1):
            first = k
            second = k + 1

            if (a[first] > a[second]):
                # Uses Swap function
                swap(a, first, second)

def displayArray(theArray):
    outList = theArray
    return outList

def maxValue(theArray):
    maxNum = 0
    for i in theArray:
        if i > maxNum:
            maxNum = i
    return maxNum

def minValue(theArray):
    minNum = theArray[0]
    for i in theArray:
        if i < minNum:
            minNum = i
    return minNum

def totalValue(theArray):
    aTotal = 0
    for s in theArray:
        aTotal += s
    return aTotal

def aveValue(theArray):
    aTotal = totalValue(theArray)
    aAverage = aTotal / len(theArray)
    return aAverage

def dataOut(theArray):
    print("The maximum value is: " + str(maxValue(theArray)))
    print("The minimum value is: " + str(minValue(theArray)))
    print("The total value is: " + str(totalValue(theArray)))
    print("The average value is: " + str(aveValue(theArray)) + "\n")

def processInput(theArray):
    print("The original array was:\n " + str(displayArray(theArray)) + "\n")
    dataOut(theArray)
    sortArray(theArray)
    print("The sorted array is:\n " + str(displayArray(theArray)))

def unitTest():
    print("Running test . . .")
    randIntArray()
    theArray = randIntArray()
    processInput(theArray)
    print("\n Finished test . . .")

def main():
    unitTest()
    theArray = []
    done = False
    while not done:
        proceedQ = input("Would you like to enter 10 numbers <y/n>? ")
        if proceedQ == "y":
            getData()
            processInput(theArray)
        if proceedQ != "y":
            done = True


main()

再次感谢所有参与的人,你们是天使。

  • 酒吧

【问题讨论】:

  • 您可能打算将getData() 返回的值存储到变量theArray 中。因此,您的 theArray 现在为空白,但在函数 minValue() 中,您正在尝试访问第一个元素。这就是抛出错误的原因
  • 您的代码不是 Python 惯用的。在 Python 中,下划线优于 CamelCase。在randIntArray函数中不需要声明randomList = [](最好命名为generate_random_array。另外,这个函数可以通过调用random.sample(range(1, 101), 10)来完全替换,不需要额外的函数-它绝对不会添加对您的代码有价值。
  • displayList 函数实际上也没有任何作用。 python中有内置的minmax函数。像aTotaltheName 这样的变量看起来很奇怪并且很难输入,你永远不会在真正的生产 python 代码中找到这样的前缀。我建议你从阅读 Python 教程开始了解基础知识和 PEP-8 学习标准 Python 编码风格。

标签: python arrays list python-3.x sorting


【解决方案1】:

main()中调用getData()时,不会将返回的userIntList赋值给theArray

更新main()代码:

def getData():
    userIntList = []
    for i in range(10):
        userNum = getInt("Please enter value number : ")
        userIntList.append(userNum)
    return userIntList

def main():
    unitTest()
    theArray = []
    done = False
    while not done:
        proceedQ = input("Would you like to enter 10 numbers <y/n>? ")
        if proceedQ == "y":
            # Assign the returned list from getdata() to theArray
            theArray = getData() 
            processInput(theArray)
        if proceedQ != "y":
            done = True

【讨论】:

    【解决方案2】:

    main() 中,当您调用函数getData() 时,您没有捕获它返回的结果。因此,当您的theArray 初始化为[] 时,它通过processInput() 以相同的值(即[])传递给minValue()。但是在minValue() 内部,当theArray 中不存在任何元素时,您将尝试访问第一个元素。您需要在 main() 中执行此操作 -

    theArray = getData()
    

    同样在 python 中,您不需要单独的函数来进行交换。可以像这样轻松完成 -

    b, a = a, b
    

    即使您不需要自己进行排序。尝试使用python提供的工具和功能

    查找列表的最大值和最小值也是如此

    【讨论】:

      猜你喜欢
      • 2014-11-03
      • 1970-01-01
      • 2015-02-11
      • 2020-04-16
      • 1970-01-01
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      • 2023-02-07
      相关资源
      最近更新 更多