Answer the question
In order to leave comments, you need to log in
Answer the question
In order to leave comments, you need to log in
Obviously, you can mix in one dimension, you can mix in another, or you can mix in both.
Usually converted to a one-dimensional list (honestly or using abstraction), shuffled, and resized.
I sketched this mixer:
import random
class Shuffler:
def __init__(self, lst, depth=2):
self.lst = lst
self.depth = depth
random.shuffle(self)
def __getlevel(self, index, depth):
curr = self.lst
curr_depth = depth
while curr_depth > 0:
curr_depth -= 1
curr_size = len(curr)
curr = curr[index % curr_size]
index //= curr_size
return curr, index
def __getitem__(self, index):
value, index = self.__getlevel(index, self.depth)
if index > 0:
raise IndexError('list index out of range')
return value
def __setitem__(self, index, value):
last_line, line_index = self.__getlevel(index, self.depth - 1)
last_line[line_index] = value
return value
def __len__(self):
acc = 1
curr = self.lst
curr_depth = self.depth
while curr_depth > 0:
curr_depth -= 1
acc *= len(curr)
if acc:
curr = curr[0]
return acc
lst = [[i * 10 + j for j in range(10)] for i in range(10)]
Shuffler(lst, 2)
print(*lst, sep='\n')
[45, 50, 74, 1, 3, 29, 43, 2, 93, 68]
[41, 10, 51, 99, 85, 20, 95, 54, 59, 8]
[46, 64, 24, 12 , 26, 15, 6, 76, 39, 5]
[58, 13, 44, 60, 36, 70, 63, 79, 42, 18]
[9, 69, 25, 66, 67, 65, 35, 47 , 23, 87]
[78, 80, 22, 73, 97, 31, 91, 75, 82, 90]
[57, 38, 49, 11, 84, 17, 62, 7, 89, 71]
[40, 30, 86, 94, 21, 53, 14, 19, 0, 32]
[33, 37, 61, 92, 81, 88, 56, 83, 98, 34]
[96, 16, 52, 4, 27, 55, 48, 72, 77, 28]
random.shuffle() - shuffles a one-dimensional array.
You can just walk through the rows of an array (two-dimensional list) and apply to each shuffle. Then apply shuffle to the array itself.
This is if the initial request implies uniform mixing of elements throughout the array.
How to shuffle a list:
from random import shuffle #из модуля "random" импортируем "shuffle"
a = [1, 2, 3, 4, "hello"] #создаём список
shuffle(a) #перемешиваем содержимое переменной "a"
print(a) #выводим переменную "a" с уже перемешенным содержимым
from random import choice #из модуля "random" импортируем "choice"
a = ["hello", 1, 10, 15, "hello world"] #создаём список
print(choice(a)) #выводим рандомное значение из переменной "a"
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question