Python: Random numbers into a list

2019-01-16 12:20发布

Create a 'list' called my_randoms of 10 random numbers between 0 and 100.

This is what I have so far:

import random
my_randoms=[]
for i in range (10):
    my_randoms.append(random.randrange(1, 101, 1))
    print (my_randoms)

Unfortunately Python's output is this:

[34]
[34, 30]
[34, 30, 75]
[34, 30, 75, 27]
[34, 30, 75, 27, 8]
[34, 30, 75, 27, 8, 58]
[34, 30, 75, 27, 8, 58, 10]
[34, 30, 75, 27, 8, 58, 10, 1]
[34, 30, 75, 27, 8, 58, 10, 1, 59]
[34, 30, 75, 27, 8, 58, 10, 1, 59, 25]

It generates the 10 numbers like I ask it to, but it generates it one at a time. What am I doing wrong?

7条回答
forever°为你锁心
2楼-- · 2019-01-16 13:06

Here I use the sample method to generate 10 random numbers between 0 and 100.

Note: I'm using Python 3's range function (not xrange).

import random

print(random.sample(range(0, 100), 10))

The output is placed into a list:

[11, 72, 64, 65, 16, 94, 29, 79, 76, 27]
查看更多
登录 后发表回答