将列表导出到CSV /空格分隔,每个子列表在其自己的列中 [英] Exporting a list to a CSV/space separated and each sublist in its own column

查看:419
本文介绍了将列表导出到CSV /空格分隔,每个子列表在其自己的列中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确定有一个简单的方法来做,所以这里。我试图将列表导出为CSV列。 (基本上,另一个程序将如何使用我生成的数据)。我有一个名为[frames]的组,其中包含[frame001],[frame002],[frame003]等等。我想要CSV文件它被生成为具有第一列[frame001]的所有值,第二列中的[frame002]等等。我以为如果我可以将文件保存为CSV,我可以在Excel中操作它,但是,我想有一个解决方案,我可以编程跳过该步骤。



是我迄今尝试使用的代码:

  import csv 

data = [frames]
out = csv.writer(open(filename,w),delimiter =',',quoting = csv.QUOTE_ALL)
out.writerow(data)

我也试过:

  import csv 

myfile = open(...,'wb')
wr = csv.writer(myfile,quoting = csv.QUOTE_ALL)
wr.writerow(mylist)

如果有办法做到这一点,所有的值都是空格分隔的,那将是理想的,但是在这一点上,我一直在尝试这么几个小时,不能绕过正确的解决方案。

解决方案

'描述的是你想翻译一个二维的数据数组。在Python中,只要内部列表的长度相同,就可以轻松实现这个 zip 函数。

  out.writerows(zip(* data))

如果他们不是长度相同,可以使用 itertools.izip_longest 来填充剩余的字段有一些默认值(甚至'')。


I'm sure there is an easy way to do this, so here goes. I'm trying to export my lists into CSV in columns. (Basically, it's how another program will be able to use the data I've generated.) I have the group called [frames] which contains [frame001], [frame002], [frame003], etc. I would like the CSV file that's generated to have all the values for [frame001] in the first column, [frame002] in the second column, and so on. I thought if I could save the file as CSV I could manipulate it in Excel, however, I figure there is a solution that I can program to skip that step.

This is the code that I have tried using so far:

import csv

data = [frames]
out = csv.writer(open(filename,"w"), delimiter=',',quoting=csv.QUOTE_ALL)
out.writerow(data)

I have also tried:

import csv

myfile = open(..., 'wb')
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(mylist)

If there's a way to do this so that all the values are space separated, that would be ideal, but at this point I've been trying this for hours and can't get my head around the right solution.

解决方案

What you're describing is that you want to translate a 2 dimensional array of data. In Python you can achieve this easily with the zip function as long as the inner lists are all the same length.

out.writerows(zip(*data))

If they are not all the same length, you can use itertools.izip_longest to fill the remaining fields with some default value (even '').

这篇关于将列表导出到CSV /空格分隔,每个子列表在其自己的列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆