将随机数写入csv文件

时间:2016-05-18 17:26:09

标签: python csv

我想输出一个csv文件,其中的行如下所示: x,y,0,1或x,y,1,0其中x和y是具有加权概率的从1到5的随机整数。不幸的是,我只是将其作为csv文件:

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

我的python代码如下所示:

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)

我做错了什么?

1 个答案:

答案 0 :(得分:2)

您可以从l中的列表中弹出项目。一旦它们为空,while len(h) > 0:永远不会为True,而while循环不会运行。请尝试复制子列表

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)

或直接枚举子列表

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)