本文介绍了Python:将随机数放入列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
创建一个名为my_randoms的列表",其中包含10个随机数字,介于0和100之间.
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)
不幸的是,Python的输出是这样的:
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]
它会像我要求的那样生成10个数字,但是一次生成一个.我在做什么错了?
It generates the 10 numbers like I ask it to, but it generates it one at a time. What am I doing wrong?
推荐答案
您可以使用 random.sample
一次调用即可生成列表:
You could use random.sample
to generate the list with one call:
import random
my_randoms = random.sample(xrange(100), 10)
这将生成(包括)0到99范围内的数字.如果想要1到100,则可以使用此数字(感谢@martineau指出了我费解的解决方案):
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:将随机数放入列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!