Python: Non Repeating Random Values From List
I am trying to write a program in python 2.7 that has to choose more than one random variable and print it out. But the variable can't be the same as any of the previously printed
Solution 1:
you can use random.sample()
random.sample(population, k)
Return a
k
length list of unique elements chosen from thepopulation
sequence. Used for random sampling without replacement.
In [13]: "+".join(random.sample(sentences,3))
Out[13]: 'a+b+c'
Solution 2:
A random value that isn't the same as previous values isn't very random.
Perhaps you'd like to use random.shuffle to just rearrange your list of items randomly, and then you can take one off at a time?
Solution 3:
May be you want random.sample
>>>mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]>>>print(sum(random.sample(mylist, 3)))
13
OR
>>>"+".join(random.sample(map(str, mylist),3)) #ifstringmap(str,) can avoid
'6+1+3'
Solution 4:
import random
def generate_random(my_list, number_of_choices):
chosen = []
cnt = 0while cnt < number_of_choices:
choice = random.choice(my_list)
if choice not in chosen:
chosen.append(choice)
cnt +=1return chosen
Solution 5:
import random
importstring
def sample_n(arr, N):
return random.sample(arr, N)
sentences = list(string.ascii_lowercase)
print"".join(sample_n(sentences, 3))
I think it would be nice to explain how to implement a sample
function without using a designated API function:
>>>arr = range(10)>>>arr
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>out = [arr.pop(random.randint(0,len(arr))) for i in xrange(3)]>>>out
[0, 1, 8]
Post a Comment for "Python: Non Repeating Random Values From List"