【问题标题】:unexpected output in producing list with random [closed]随机生成列表中的意外输出[关闭]
【发布时间】:2022-08-19 00:27:57
【问题描述】:

我希望通过以下代码制作一个包含 10 个随机数的列表 但我的输出是一个空列表

我不知道为什么 python 不生成列表 有人能帮助我吗?

这是我的代码:

import random
box=[]
for x in box:
    counts=len(box)
    if counts < 10:
        num=random.randint(1,100)
        box.append(num)
print(box)
  • shouldn\'t use an image here。您在图像中提供的内容可以表示为格式化为代码的文本。您可以edit您的帖子进行更改。
  • 循环永远不会运行,因为for x in box 没有任何东西可以迭代。
  • box = [random.randint(1, 100) for _ in range(10)]

标签: python


【解决方案1】:

box 是空的,所以到 for 循环将不起作用。 解决方案:

import random
box = []
counts = len(box)
while(counts < 10):
    num=random.randint(1, 100)
    box.append(num)
    counts = len(box)
print(box)

您需要将if 替换为while 并在每次迭代时更新counts

【讨论】:

  • 如果你需要做一些n 次的事情,使用for _ in range(n) 循环更pythonic,不需要任何额外的变量。
  • 非常感谢<3
【解决方案2】:

正如 Yevhen Kuzmovych 所建议的,最 Pythonic 的方式是:

box = [random.randint(1, 100) for _ in range(10)]

另一种简单快捷的方法是使用 numpy 库

import numpy as np
box = np.random.randint(1, 100, size=10)

【讨论】:

    【解决方案3】:

    因为你给的是一个空盒子。当涉及到带有 x 的 for 循环时。所以它理解你在列表中有 0 个元素。它会立即打破循环。 试试while循环。

    import random
    
    running = 0
    Box = []
    while running <= 10:
        Box.append(random.randint(1,100))
        running +=1
    
    print(Box)
    

    【讨论】:

    • 请至少使它在语法上正确。
    猜你喜欢
    • 2023-03-24
    • 2023-02-03
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多