1

I have the following:

list1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"]

for i in range(3):
        print(random.sample(list1, k=1))
        print(random.sample(list1, k=1))
        print(random.sample(list1, k=1))

and am looking for something like:

['a', 'g', 'i']
['c', 'h', 'b']
['k', 'd', 'e']

The idea being to have no repeats anywhere.

I understand that I could slice the list if not using a loop, but am unsure of how to go about it with the loop involved.

Dean Arvin
  • 115
  • 6

5 Answers5

5

Just shuffle it and take subsequent slices:

list1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"]
random.shuffle(list1)

N = 3

for i in range(0, len(list1)-N+1, N):
    print(list1[i:i+N])

#['c', 'b', 'd']
#['i', 'e', 'j']
#['h', 'g', 'f']
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
4

Shuffle the list then break it apart:

import random

list1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"]
random.shuffle(list1)
for i in range(0, len(list1), 3):
    print(list1[i:i+3])
Anonymous
  • 11,748
  • 6
  • 35
  • 57
1

You could also use you're original sample function and slice the list using list comprehensions:

list1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"]

output = random.sample(list1, k=9)
output = [output[i:i+3] for i in range(0,9,3)]
Jay Mody
  • 3,727
  • 1
  • 11
  • 27
1

Input:

import random
list1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"]

for i in range(3):
  print([list1.pop(random.choice(range(len(list1)))) for i in range(3)])

Output:

['j', 'g', 'b']
['f', 'c', 'h']
['e', 'k', 'i']
Petar Luketina
  • 449
  • 6
  • 18
1
>>> list1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"]
>>> mylist = random.sample(list1, k=9)
>>> print([mylist[i:i+3] for i in range(0, 9, 3)])

output [['e', 'b', 'i'], ['k', 'h', 'd'], ['j', 'f', 'a']]

Salim
  • 2,046
  • 12
  • 13
  • This answer is same as Jay's. While I posted this I didn't see Jay's answer as I was busy finding my own answer. – Salim Dec 28 '19 at 05:19