python将数放入列表_Python:将随机数放入列表

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?

解决方案

You could use random.sample to generate the list with one call:

import random

my_randoms = random.sample(xrange(100), 10)

That generates numbers in the (inclusive) range from 0 to 99. If you want 1 to 100, you could use this (thanks to @martineau for pointing out my convoluted solution):

my_randoms = random.sample(xrange(1, 101), 10)

你可能感兴趣的:(python将数放入列表)