简体   繁体   中英

How to get the position of a random number generated in a python list.?

I have a numeric list. I need pick a random number in a numeric list and know position number found in list. random.choice(name_list) just find a random number but I am at the same time in need of a random number position

generate random indexes to use instead.

import random
a = [1,2,3,4,5]
rand_num = random.randrange(len(a))
print(a[rand_num])
import random
sample_list = [1,2,3,4,5]
# this should be work for multiple same value indexes
# EX: sample_list = [1,2,3,2,2] 
# if random number is 2 than below code will print indexes 1, 3, 4
random_number = random.choice(sample_list)
for i in [i for i,x in enumerate(sample_list) if x == random_number]:
    print(i) # print the indexes or random number

You could also get the index and the random number in one operation using enumerate()

index,number = random.choice(list(enumerate(a)))

This not very efficient however and, if you're doing this often or on a very big list, you should do it in two steps

index   = random.randrange(len(a))
number  = a[index]

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