Python creating a list of list

user11862897

I would like to know if there was a better way to create a list of list in which each list is a random permutation of an other list. This is what I coded to do it assuming numpy.random is import as rd :

def shuffle(L):
    i = rd.randint(0,len(L))
    j = rd.randint(0,len(L))
    L[i], L[j] = L[j], L[i]
    return 

list_base= [0,1,2,3]
list_of_list=[]
for k in range(4):
    M = list_base
    for i in range(5):
        shuffle(M)
    list_of_list.append(M[:])
AKX

Use random.shuffle?

import random
input_list = [0,1,2,3]
shuffled_lists = []
for x in range(4):
  lst = input_list[:]  # copy, since ...
  random.shuffle(lst)  # ... this modifies it in-place
  shuffled_lists.append(lst)

print(shuffled_lists)

outputs e.g.

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

This will not guarantee that all permutations in shuffled_lists are unique though!

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related