Lin*_*ang 47 python random list
创建一个名为my_randoms的"列表",其中包含0到100之间的10个随机数.
这是我到目前为止:
import random
my_randoms=[]
for i in range (10):
my_randoms.append(random.randrange(1, 101, 1))
print (my_randoms)
Run Code Online (Sandbox Code Playgroud)
不幸的是Python的输出是这样的:
[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]
Run Code Online (Sandbox Code Playgroud)
它会像我要求的那样生成10个数字,但它会一次生成一个.我究竟做错了什么?
rob*_*lep 77
您可以使用random.sample一次调用生成列表:
import random
my_randoms = random.sample(xrange(100), 10)
Run Code Online (Sandbox Code Playgroud)
这会产生从0到99的(包括)范围内的数字.如果你想要1到100,你可以使用它(感谢@martineau指出我复杂的解决方案):
my_randoms = random.sample(xrange(1, 101), 10)
Run Code Online (Sandbox Code Playgroud)
mat*_*exx 41
import random
my_randoms = [random.randrange(1, 101, 1) for _ in range(10)]
Run Code Online (Sandbox Code Playgroud)
kar*_*ikr 17
修复print语句的缩进
import random
my_randoms=[]
for i in range (10):
my_randoms.append(random.randrange(1,101,1))
print (my_randoms)
Run Code Online (Sandbox Code Playgroud)
在这里,我使用该sample方法生成0到100之间的10个随机数.
注意:我正在使用Python 3的range功能(不是xrange).
import random
print(random.sample(range(0, 100), 10))
Run Code Online (Sandbox Code Playgroud)
输出放在一个列表中:
[11, 72, 64, 65, 16, 94, 29, 79, 76, 27]
Run Code Online (Sandbox Code Playgroud)
小智 7
这很晚了,但万一有人发现这有用。
您可以使用列表推导。
rand = [random.randint(0, 100) for x in range(1, 11)]
print(rand)
Run Code Online (Sandbox Code Playgroud)
输出:
[974, 440, 305, 102, 822, 128, 205, 362, 948, 751]
Run Code Online (Sandbox Code Playgroud)
干杯!
| 归档时间: |
|
| 查看次数: |
184373 次 |
| 最近记录: |