Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python将整数列表作为列添加到CSV_Python_List_Csv - Fatal编程技术网

Python将整数列表作为列添加到CSV

Python将整数列表作为列添加到CSV,python,list,csv,Python,List,Csv,我有3个整数列表,格式如下: a = [1,2,3] b = [4,5,6] c = [7,8,9] 我正在尝试以以下格式将这些内容输入CSV文件,每个列表中的每个项目取一行,每个列表取一个新列: 1 4 7 2 5 8 3 6 9 目前,我的代码(如下)能够将第一个列表添加到CSV中,尽管我在以我希望的方式添加第二个和第三个列表时遇到困难 with open('Test.csv', 'wb') as f: for item in a: csv.write

我有3个整数列表,格式如下:

a = [1,2,3]
b = [4,5,6]
c = [7,8,9]
我正在尝试以以下格式将这些内容输入CSV文件,每个列表中的每个项目取一行,每个列表取一个新列:

1  4  7
2  5  8
3  6  9
目前,我的代码(如下)能够将第一个列表添加到CSV中,尽管我在以我希望的方式添加第二个和第三个列表时遇到困难

with open('Test.csv', 'wb') as f:
    for item in a:
        csv.writer(f).writerow([item])
提供CSV输出:

1
2
3
1
2
3
4
5
6
如果我仅使用以下代码,则b列表将添加到同一列中,我要求将其插入到第二列中:

for itemB in b:
        csv.writer(f).writerow([itemB])
提供CSV输出:

1
2
3
1
2
3
4
5
6
我怎样才能做到这一点

zip(a,b,c)
提供一个行列表:
[(1,4,7)、(2,5,8)、(3,6,9)]

这项工作:

a = [1,2,3]
b = [4,5,6]
c = [7,8,9]

with open('/tmp/test.csv','wb') as out:
    for row in zip(a,b,c):
        csv.writer(out, delimiter=' ').writerow(row)
甚至:

with open('/tmp/test.csv','wb') as out:
    csv.writer(out, delimiter=' ').writerows(zip(a,b,c))
输出:

$ cat /tmp/test.csv
1 4 7
2 5 8
3 6 9

为了更接近OP的输出,我认为您可能必须指定分隔符。为简洁起见,您可以将最后两行替换为
csv.writer(out,delimiter='').writerows(zip(a,b,c))