Bat
Bat

Reputation: 155

Split list into random sub lists and assign three randomised values to each element in sub lists

I am using the below code currently to split a list into two equal sub lists as below.

Group 1 = [2, 5, 6, 8, 10, 14, 15, 16]

Group 2 = [1, 3, 4, 7, 9, 11, 12, 13]

import random

# Split list into two sub lists
#def sub_lists():

data = list(range(1, 17))
random.shuffle(data)
Group1, Group2 = sorted(data[:8]), sorted(data[8:])
print(Group1, Group2)

# assign randomised values to elements in each group
for i in Group1:
   Tasks = ['A', 'B','C']
   random.shuffle(Tasks)
   with open('Group1_allocation.txt', 'a') as f:
      f.write(f'{i} = {Tasks}\n')


for j in Group2:
   Tasks = ['A', 'B','C']
   random.shuffle(Tasks)
   with open('Group2_allocation.txt', 'a') as f:
      f.write(f'{j} = {Tasks}\n')

And then assign each element in the sub lists (Group1 and Group 2) three randomised values from a new list (Tasks) such that I get the following output in each fle.

Group1_allocation.txt

2 = ['A', 'B', 'C']

5 = ['B', 'A', 'C']

6 = ['C', 'A', 'B']

8 = ['B', 'A', 'C']

10 = ['C', 'B', 'A']

14 = ['B', 'C', 'A']

15 = ['A', 'C', 'B']

16 = ['C', 'A', 'B']

The script works, but contains repeated code. How could this be coded cleaner/better ?

Upvotes: 0

Views: 75

Answers (1)

ExplodingGayFish
ExplodingGayFish

Reputation: 2897

Here is one way with one less loop:

import random

data = list(range(1, 17))
random.shuffle(data)
l = len(data)

Tasks = ['A', 'B','C']
for i,d in enumerate(data):
    filename = 'Group{}_allocation.txt'.format(int(1 + i // (l / 2)))
    with open(filename, 'a') as f:
        f.write(f'{data[i]} = {Tasks}\n')

Upvotes: 1

Related Questions