概述
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将数放入列表,Python:将随机数放入列表的全部内容,希望文章能够帮你解决python将数放入列表,Python:将随机数放入列表所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复