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?
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.