简体   繁体   中英

Python: Shuffle function

I have a list like the following:

lst = [0, 1, 3, 4]

After random.shuffle(lst) the resulted lst might be something like [4, 0, 3, 1] .

Is there a way for the subsequent of random.shuffle(lst) I won't get the list I already got before without having to save the list after each shuffle?

The following logic work in the case where you just dont want 2 adjacent pemutation to be identical:

import itertools
import random

def noRep(prev_idx, perm):
    while True:
        r = random.randint(0, len(perm) - 1)
        if r != prev_idx:
            return r

perm_l = list(map(list,itertools.permutations([1, 2, 3])))
idx = random.randint(0, len(perm_l) - 1)
print(perm_l[idx])
idx = noRep(idx, perm_l)
print(perm_l[idx])
idx = noRep(idx, perm_l)
print(perm_l[idx])

The output is:

[1, 2, 3]
[3, 1, 2]
[1, 2, 3]

As you can see the third and the first are the same, to get different permutation each time you should save the indices that was randomly chosen and avoid choosing them. In this case you should also alter the while True loop to avoid endless loop.

In the case you dont want to generate all the permutations you can use choice and select from specific values that of constantly changing.

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