【问题标题】:Generate a list of random numbers生成随机数列表
【发布时间】:2018-04-08 16:55:18
【问题描述】:

因此,任务是询问用户他们想要在列表中随机生成多少个数字,然后从该列表中找到:总数(总和)、平均值、最小和最大数字。 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()

【问题讨论】:

  • 您可能会收到错误消息,因为您正在执行len(int(average)),正如错误所示。可能值得将您的循环更改为其他内容?
  • average是一个数字,不能在上面应用len
  • 查看有问题的代码行,并用您自己的英文单词向自己解释它应该如何工作。然后逐步分解它,并解释它实际上是如何尝试按书面方式工作的。注意到断开了吗?

标签: python python-3.x list random


【解决方案1】:

这是您的代码的工作版本。

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 语句返回值的习惯,并将格式化作为与计算函数分开的一个步骤。

【讨论】:

  • 我知道你的意思是好的,但是应该劝阻 OP 的问题。这不是人们学习编程基础的好地方,尤其不是调试;它更适合填补领域知识的空白。目标是让第三方能够通过搜索找到关于 SO 的解决方案 - 每个新程序员都有细微不同的调试问题,并且不知道除了唾手可得的果实之外要搜索什么(“FooError? ") 这在几年前就已经被很好地覆盖了。
  • @KarlKnechtel,经过反思,通过代码转储和几句话,您可能是对的。问题是 SO 还没有为此做好准备。我们金徽章持有者需要很长时间才能结束一个问题(真的需要我们 5 个人吗?),这是避免六个糟糕/不完整答案的唯一方法。 Meta 上有很多人要求为金/银标签徽章提供更多功能,但实际上没有人关心。
  • 我很喜欢大家对我哪里出错的建议和意见。我确实尽我所能避免在这里发帖,除非这是我最后的手段,而且我还没有找到任何其他类似于错误或问题的解决方案,主要是因为人们开始抱怨有些人在没有的情况下使用它自己做研究。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    • 2021-08-21
    相关资源
    最近更新 更多