繁体   English   中英

如何使用python从所需范围生成随机数

[英]How to generate random number from desired range using python

我有一个包含9000个列表项作为字符串的列表,我想在其中随机选择4000个实例。 我怎么能做到这一点。 我已经写下了代码。

from random import randint
for r in range(9000):
    print(randint(9000))
  1. 首先,我将生成4000个随机数
  2. 然后列表成员将被选定的随机数所拾取我写下了一个代码,该代码显示错误代码如下

使用random.sample

from random import sample

my_list = [1,2,3,4,5,5,4]

print(sample((my_list), 5)) # you would change 5 to 4000

附带说明一下,如果您想从结果中删除重复项,则可以在python中使用一组作为重复项,不允许重复项,这是另一个示例

my_list = [1, 2, 3, 4, 5, 5, 4, 6, 5, 3, 2, 12]

result = set(sample((my_list), 5)) # you would change 5 to 4000
print(result)

#set might remove duplicates so you wont have the desired number of items again
while len(result) < 5: # length of your list
    rand = choice(my_list)
    result.add(rand)

print(result)

非常简单,尝试这样的事情

import random
for x in range(100):
  print random.randint(100,150)*2,
print

然后你得到

290 268 200 266 238 284 220 246 294 226 208 268 298 206 210 260 206 250 264 290 298 212 262 258 222 272 298 226 248 260 278 254 236 296 264 224 240 246 220 210 232 242 240 272 276 272 240 256 242 252 202 234 280 216 238 290 236 258 262 208 236 252 254 238 276 256 220 266 258 258 202 250 262 204 252 218 242 276 222 218 262 290 286 300 262 202 228 218 248 202 264 226 242 208 220 224 238 240 236 250

因此,只需选择您的范围。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM