Write your own function to randomly shuffle the elements in the list
Randomly select the original list index, exchange the value at the index position
import random
def random_list1(li):for i inrange(0,100):
index1 = random.randint(0,len(li)-1)
index2 = random.randint(0,len(li)-1)
li[index1], li[index2]= li[index2], li[index1]return li
li =[1,2,3,4,5]
test =random_list1(li)print(test)
First generate a copy of the original list a_copy, create a new empty list result, and then randomly select the values in the copy list to store in the empty list result, and then delete
import random
def random_list2(a):
a_copy = a.copy()
result =[]
count =len(a)for i inrange(0, count):
index = random.randint(0,len(a_copy)-1)
result.append(a_copy[index])
del a_copy[index]return result
test =[1,3,4,5,6]
result =random_list2(test)print(result)
import random
test =[1,2,3,4,5]
random.shuffle(test)print(test)
Python's random.shuffle() function can be used to shuffle a sequence. It shuffles the sequence itself, rather than generating a new sequence.
def shuffle(self, x, random=None):"""Shuffle list x in place, and return None.
Optional argument random is a 0-argument function returning a
random float in[0.0,1.0);if it is the default None, the
standard random.random will be used."""
if random is None:
randbelow = self._randbelow
for i inreversed(range(1,len(x))):
# pick an element in x[:i+1]with which to exchange x[i]
j =randbelow(i +1)
x[i], x[j]= x[j], x[i]else:
_ int = int
for i inreversed(range(1,len(x))):
# pick an element in x[:i+1]with which to exchange x[i]
j =_int(random()*(i +1))
x[i], x[j]= x[j], x[i]
Recommended Posts