Choosing a random list item in python

I am trying to create a function that takes two lists and selects an element randomly from each of them. Is there a way to do this using the random.seed function?

+4
source share
3 answers

You can use random.choice to select a random item from a sequence (like a list).

If your two lists are list1 and list2 , this will be:

 a = random.choice(list1) b = random.choice(list2) 

Are you sure you want to use random.seed ? This will initialize the random number generator each time, which can be very useful if you want subsequent runs to be identical, but overall this is undesirable. For example, the following function will always return 8, although it looks like it should arbitrarily select a number from 0 to 10.

 >>> def not_very_random(): ... random.seed(0) ... return random.choice(range(10)) ... >>> not_very_random() 8 >>> not_very_random() 8 >>> not_very_random() 8 >>> not_very_random() 8 
+19
source

Note. @FJ's solution is much less complicated and better.


Use random.randint to select a pseudo-random index from the list. Then use this index to select the item:

 >>> import random as r >>> r.seed(14) # used random number generator of ... my head ... to get 14 >>> mylist = [1,2,3,4,5] >>> mylist[r.randint(0, len(mylist) - 1)] 

You can easily expand this to work on two lists.

Why do you want to use random.seed ?


Example (using Python2.7):

 >>> import collections as c >>> c.Counter([mylist[r.randint(0, len(mylist) - 1)] for x in range(200)]) Counter({1: 44, 5: 43, 2: 40, 3: 39, 4: 34}) 

Is this random enough?

+1
source

I completely changed my previous answer. Here is a class that wraps a random number generator (with extra seed) with a list. This is a minor improvement over FJ as it provides deterministic behavior for testing. The choice() call in the first list should not affect the second list and vice versa:

 class rlist (): def __init__(self, lst, rg=None, rseed=None): self.lst = lst if rg is not None: self.rg = rg else: self.rg = random.Random() if rseed is not None: self.rg.seed(rseed) def choice(self): return self.rg.choice(self.lst) if __name__ == '__main__': rl1 = rlist([1,2,3,4,5], rseed=1234) rl2 = rlist(['a','b','c','d','e'], rseed=1234) print 'First call:' print rl1.choice(),rl2.choice() print 'Second call:' print rl1.choice(),rl2.choice() 
-1
source

Source: https://habr.com/ru/post/1384170/


All Articles