生成随机数列表

时间:2018-04-08 16:55:19

标签: python python-3.x list random

因此,分配是询问用户在列表中需要多少随机生成的数字,然后从该列表中找到:总(总和),平均值,最小值和最大值。 SOFAR,我在第14行收到错误“类型'int'的对象没有len()”。使用<时,我得到相同的响应太。

import random


def main():

    randomList = 0    
    smallest = 0
    largest = 0
    average = int(input("How may numbers (between 1-100) would you like to generate?: "))
    total = 0
    if average >= 101 or average <= 0:
        print("Invalid input:How may numbers (between 1-100) would you like to generate?: ")
    else:
         while randomList != len(int(average)):
            randomList.append(random.randint(1,101))
    randomList=sorted(randomList)
    print(randomList)
    total = sum(randomList)
    average = float(sum(randomList)) / max(len(randomList))
    largest = randomList.pop(average)
    smallest = randomList.pop(0)

    print('The total of all the numbers are ',str(total))
    print('The average of all the numbers are ',str(average))
    print('The largest of all the numbers are ',str(largest))
    print('The smallest of all the numbers are ',str(smallest))
main()

2 个答案:

答案 0 :(得分:0)

以下是您的代码的工作版本。

import random

def main():

    smallest = 0
    largest = 0
    n = int(input("How may numbers (between 1-100) would you like to generate?: "))
    total = 0
    if n >= 101 or n <= 0:
        print("Invalid input:How may numbers (between 1-100) would you like to generate?: ")
    else:
        randomList = random.choices(range(1, 101), k=n)
    print(randomList)
    total = sum(randomList)
    average = sum(randomList) / len(randomList)
    largest = max(randomList)
    smallest = min(randomList)

    print('The total of all the numbers are ',str(total))
    print('The average of all the numbers are ',str(average))
    print('The largest of all the numbers are ',str(largest))
    print('The smallest of all the numbers are ',str(smallest))

main()

<强>解释

许多错误已得到修复:

  • 使用random.choices获取指定长度值的随机列表。
  • 您在数字列表和average值的上下文中使用average。确保正确命名和使用变量。
  • 您的算法不需要排序。
  • 我更正了averagelargestsmallest的计算。

此外,我建议您养成通过return语句返回值的习惯,并将格式设置作为与计算功能分开的步骤。

答案 1 :(得分:-2)

怎么样:     randomList = [random.integer()for i in range(userinput)]