Today, on the basis of answers I got here, I wrote this little code to create a random list of 16 elements.
import random
sources = ['Prone', 'Supine', 'Halfway', 'HalfInv']
result = [random.choice(sources)]
repeats = 0
fail = 0
while len(result) < 16:
elem = random.choice(sources)
repeats = result.count(elem)
print(repeats)
if (elem != result[-1]) & (repeats < 4):
result.append(elem)
else:
fail = fail + 1
print(fail)
if fail > 100:
result = [random.choice(sources)]
print(result)
Now what I’d like to do is:
1. to create 2 random lists naming them differently (how do I do this based on the for loop counter?)
2. put those 2 lists as columns in a tab delimited (txt) file, one next to the other in order to easily copy paste them in an excel file. I looked into csv module but it seems to only have methods for rows.
If you’re looking for a more efficient way to get a randomly ordered list of 4-of-each of your list elements from sources, try
random.shuffle(list):Next, you wanted to generate and name the lists based on the loop counter… I’d recommend against this. Instead just append your random lists into a list one at a time, and you can index them in the order they were appended.
But this still leaves you with the problem that your data is in two separate lists. To remedy this you want the
zip()function. It joins each element in list 1 with its correspondingly indexed element in list 2, forming a tuple at each index. This can be done with an arbitrary number of sequences.To zip together your lists-within-a-list, use the
*star unpacking operator before the name of your meta-list.Now you want to output to a csv file; it’s easy enough to just write your own csv function. Remember that the column delimiters ate commas, the row delimiters are newlines.
From here just pass your zipped list combo into the out_csv function, and make sure your filename has the
.csvextension. Excel can natively read in.csvfiles so you shouldn’t need to do any copy-pasting.Here’s the last step: