简体   繁体   English

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

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

i have a list with 9000 list items as strings, i want to select 4000 instances randomly amongst them. 我有一个包含9000个列表项作为字符串的列表,我想在其中随机选择4000个实例。 how can i achieve this. 我怎么能做到这一点。 I have write down a code. 我已经写下了代码。

from random import randint
for r in range(9000):
    print(randint(9000))
  1. first i will generate the random 4000 random number 首先,我将生成4000个随机数
  2. and then list members will be picked up by the selected random numbers I have write down a code which is showing an error code is as given bellow 然后列表成员将被选定的随机数所拾取我写下了一个代码,该代码显示错误代码如下

use random.sample 使用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

As a side note If you want to remove duplicates from your result you can use a set as sets in python don't allow duplicate items, another example 附带说明一下,如果您想从结果中删除重复项,则可以在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)

It is very simple.Try something like this 非常简单,尝试这样的事情

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

Then you get 然后你得到

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

So just choose your range. 因此,只需选择您的范围。

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

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