Python Csvwriter Randomize Rows

458 Views Asked by At

Is it possible to make a randomizer that randomizes entire rows using the csvwriter? The code I have is similar to this:

 for i in range(45):
    count=count+1
    writer.writerow((count,pattern))

Where pattern is a number which corresponds to count. For example: when count=1 pattern=1; count=2 pattern=9; count=3 pattern=17, and so on... I want a way to randomize the rows so that the correct count corresponds to the correct pattern still. Any help is greatly appreciated!

2

There are 2 best solutions below

0
On BEST ANSWER

Load it into a two dimensional array storing the count in a[i][0] and the pattern in a[i][1] then shuffle then write them to the csv file.

import random

count = 0
a = []
for i in range(45):
    count = count + 1
    a.append([count,pattern])

random.shuffle(a)
for i in range(len(a)):
    writer.writerow(a[i][0], a[i][1]) #a[i][0] = count, a[i][1] = pattern
0
On

This is not really a csvwriter specific question, but the way I understand your question is that you want to write random 'counts' to your csv file, that correspond to a set number. I'm not sure if your pattern in this case is n + 8, but that's how it would look like. One option would be to just create a dictionary with the pattern, select key from the dictionary and then select the value and write them. Like so:

import random
dict = {}
n = 1
for i in range(n):
   n += 8
   dict[i+1] = n

for i in range(a):
    count = random.randint(1,n)
    row = (count, dict[count])
    writer.writerow(row)