简体   繁体   中英

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. 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
  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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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