Вместо того, чтобы думать об этом в терминах «строк» и «столбцов», эквивалентный способ - рассматривать проблему как три отдельных списка номеров, разбивая каждый список на 3 группы, а затем выбирая по 3 номера каждый из каждой из них.9 групп, так что их соответствующие позиции индекса не повторяются ни в одном из 3 списков (например, если мы в итоге выберем номер в 6-й позиции 2-го фрагмента списка «a», то мы не сможем выбрать номерна 6-й позиции во 2-ом блоке списков 'b' или 'c').
Вы можете использовать numpy.array_split
, чтобы разбить список на 3 примерно равные части.Модуль random
предоставляет вам удобную функцию random.sample()
, которая позволяет вам выбирать 3 случайных числа из каждого набора, всего 9 чисел.Но, к сожалению, поскольку нам нужно отслеживать, какие индексные числа мы использовали, мы должны учитывать это. Вот один из подходов:
import random
import numpy
def process_list(original_list, exclude_indices):
# Sort the list
original_list.sort()
# Split the list into a list of 3 sublists, each about the same size
mylist_split = [arr.tolist() for arr in numpy.array_split(original_list, 3)]
# Go through each sublist, checking the corresponding list of indices in exclude_indices
number_choices = [ ]
for i in range(3):
# Look at each chunk of numbers in mylist_split. If the length is n, then generate
# a random list of numbers between 0 and n-1 (inclusive), EXCLUDING any index numbers
# found in exclude_indices[i].
possible_positions = [ j for j in range(len(mylist_split[i])) if j not in exclude_indices[i] ]
# Pick 3 random index numbers of what's available. Then pick the corresponding
# numbers in those positions.
chosen_indices = random.sample(possible_positions, 3)
for k in chosen_indices:
number_choices.append(mylist_split[i][k])
# Update exclude_indices[i] to keep track.
exclude_indices[i] += chosen_indices
return number_choices, exclude_indices
# Generate some random lists of numbers to work with
length = 50
a = [int(100*random.random()) for i in range(length) ]
b = [int(100*random.random()) for i in range(length) ]
c = [int(100*random.random()) for i in range(length) ]
exclude_indices = [ [], [], [] ]
a_choices, exclude_indices = process_list(a, exclude_indices)
b_choices, exclude_indices = process_list(b, exclude_indices)
c_choices, exclude_indices = process_list(c, exclude_indices)
print("a is", a)
print("Chosen numbers: ", a_choices)
print("b is", b)
print("Chosen numbers: ", b_choices)
print("c is", c)
print("Chosen numbers: ", c_choices)