0

I want to output a csv-file where the lines look like this: x,y,0,1 or x,y,1,0 where x and y are random integers from 1 to 5 with weighted probabilities. Unfortunately I get just this as a csv-file:

4,4,0,1
0,1
0,1
3,4,1,0
1,0
0,1
1,0
0,1
1,0
0,1

My python code looks like this:

import csv
import random
import numpy

l = [[[10,20,50,10,10],[20,20,20,20,20]],[[10,20,50,10,10],[20,20,20,20,20]]]

with open("test.csv", "wb") as f:
    writer = csv.writer(f)
    for i in range(10):
        x = random.randint(0,1)
        h = l[x]
        d =[]
        while len(h) > 0:
            a=numpy.array(h.pop(0))
            d.append(numpy.random.choice(range(1, 6), p=a/100.0))
        c = [0] * 2
        c[x]=1
        writer.writerow(d+c)

What do I do wrong?

1 Answer 1

2

You pop items from the lists in l. Once they are empty, while len(h) > 0: is never True and the while loop doesn't run. Try copying the sublists instead

import csv
import random
import numpy

l = [[[10,20,50,10,10],[20,20,20,20,20]],[[10,20,50,10,10],[20,20,20,20,20]]]

with open("test.csv", "wb") as f:
    writer = csv.writer(f)
    for i in range(10):
        x = random.randint(0,1)
        h = l[x][:]                # <-- copy list
        d =[]
        while len(h) > 0:
            a=numpy.array(h.pop(0))
            d.append(numpy.random.choice(range(1, 6), p=a/100.0))
        c = [0] * 2
        c[x]=1
        writer.writerow(d+c)

Or enumerate the sublist directly

import csv
import random
import numpy

l = [[[10,20,50,10,10],[20,20,20,20,20]],[[10,20,50,10,10],[20,20,20,20,20]]]

with open("test.csv", "wb") as f:
    writer = csv.writer(f)
    for i in range(10):
        x = random.randint(0,1)
        d =[]
        for h in l[x]:                # <-- enumerate list
            a=numpy.array(h)
            d.append(numpy.random.choice(range(1, 6), p=a/100.0))
        c = [0] * 2
        c[x]=1
        writer.writerow(d+c)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.