[英]Writing in a tabular format to a csv file
I have two lists which I am trying to write to a csv file in a specific format. 我有两个列表,我正尝试以特定格式写入csv文件。 Lets call these lists
colHead
and rowVals
. 让我们将这些列表
colHead
和rowVals
。 The list colHead
contains names of the column headers which need to be written to a csv file. 列表
colHead
包含需要写入csv文件的列标题的名称。 I have achieved this using the following code: 我使用以下代码实现了这一点:
with open(filename, 'wb') as f:
writer = csv.writer(f)
writer.writerow(colHead)
Now, rowVals
is a list which contains 250 values. 现在,
rowVals
是一个包含250个值的列表。 These 250 values, are arranged in an orderly format. 这250个值以有序格式排列。 I wish to write every 25 values from
rowVals
under each colHead
to achieve the results. 我想从每25个值写入
rowVals
每个下colHead
达到的结果。
The code I am using (it is not giving me the desired results) is: 我正在使用的代码(没有给我期望的结果)是:
with open(filename, 'wb') as f:
writer = csv.writer(f)
writer.writerow(colHead)
for i in range(0,25):
writer.writerow(rowVal)
i+=25
Finally I want to write this format to the csv format. 最后,我想将此格式编写为csv格式。
colHead1,colHead2,colHead3......colHead10
rowVal1, rowVal26, . , .
rowval2, rowVal27, . , .
. , . , . , .
. , . , . , .
rowVal25, . , . , rowVal250
Please let me know where I am going wrong as well. 也请让我知道我要去哪里。
just feed writerows
with a generator comprehension slicing your 250-item list with a step of 25 like this, 25 times: 只需使用生成器理解提要
writerows
,就可以像这样以25步将您的250个项目列表切片25次:
writer.writerows(rowVal[i::25] for i in range(25))
I get: 我得到:
rowval1,rowval26,rowval51,rowval76,rowval101,rowval126,rowval151,rowval176,rowval201,rowval226
rowval2,rowval27,rowval52,rowval77,rowval102,rowval127,rowval152,rowval177,rowval202,rowval227
rowval3,rowval28,rowval53,rowval78,rowval103,rowval128,rowval153,rowval178,rowval203,rowval228
...
rowval24,rowval49,rowval74,rowval99,rowval124,rowval149,rowval174,rowval199,rowval224,rowval249
rowval25,rowval50,rowval75,rowval100,rowval125,rowval150,rowval175,rowval200,rowval225,rowval250
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.