创建随机数列表

时间:2014-10-11 12:26:58

标签: python list random

作业(但我写了自己的代码):

  

询问用户的尺寸L_size,并创建一个列表L,其中包含L_size个实数。数字应该随机生成(随机生成器应该给出种子0)。使用以下行导入,播种和使用随机生成器:

import random  # Place it at the top of your program. Do it only once.

random.seed(0) # Place this after the import statements. Seed with 0. Do it only once.

num = random.random() # Call this whenever you want a new, random number.

所以我到目前为止编写了这段代码。

import random
random.seed(0)
num = random.random()
L_size = float(input("Enter a real number: "))
L = []
for L_size in range(num):
    L.append(num)
print (L)

它显示了一个错误:

for L_size in range(num):
TypeError: 'float' object cannot be interpreted as an integer. "

如何解决此问题?

3 个答案:

答案 0 :(得分:0)

num = random.random()应该是num = random.randint(1,100)

range需要integer而不是float

查看您的问题,您应该将L_size传递给range而不是num,这应该是int而不是float

L_size = int(input("Enter a real number: "))

完整代码:

import random
random.seed(0)
L_size = int(input("Enter a real number: ")) # int to pass to range
L = []
for _ in range(L_size):
    num = random.random() # create random num and append
    L.append(num)
print (L)

或使用列表理解:

import random
random.seed(0)
L_size = int(input("Enter a real number: "))
L = [ random.random() for _ in range(L_size)]
print (L)

答案 1 :(得分:0)

这将按照您的要求进行

from random import random, seed

seed(0)
L_size = int(input('Enter the size of the list: '))
L = [ random() for i in range(L_size) ]
print(L)

<强>输出

Enter the size of the list: 4
[0.8444218515250481, 0.7579544029403025, 0.420571580830845, 0.25891675029296335]

答案 2 :(得分:-1)

您需要让用户输入列表的大小,然后创建一个实数列表;但是在你的代码中,你正在使用一些随机数的范围。

您的代码还存在其他一些问题,请参阅评论:

import random
random.seed(0)
num = random.random()
L_size = float(input("Enter a real number: ")) # this is how big your list should be
L = [] # This is the empty list you are going to add numbers to.
for L_size in range(num): # Here, you need L_size not num
    L.append(num) # here, you need to call random.random() each time,
                  # otherwise you will have a list with the same random
                  # number duplicated
print (L)

我希望这可以帮助您完成作业。