我是脚本新手.我有一个表 (Table1.txt),我需要创建另一个表,其中 Table1 的行按列排列,反之亦然.我已经找到了针对 Perl 和 SQL 而不是 Python 的解决方案.
I'm new to scripting. I have a table (Table1.txt) and I need to create another table that has Table1's rows arranged in columns and vice versa. I have found solutions to this problem for Perl and SQL but not for Python.
我两天前才开始学习 Python,所以就我所掌握的:
I just started learning Python two days ago, so this is as far as I got:
import csv import sys with open(sys.argv[1], "rt") as inputfile: readinput = csv.reader(inputfile, delimiter=' ') with open("output.csv", 'wt') as outputfile: writer = csv.writer(outputfile, delimiter=" ") for row in readinput: values = [row[0], row[1], row[2], row[3]] writer.writerow([values])这只是将列复制为列.我现在想做的是将最后一行写为 writer.writecol([values]) 但似乎没有这样的命令,我还没有找到另一种写法行作为列.
This just reproduces the columns as columns. What I would have liked to do now is to write the last line as writer.writecol([values]) but it seems that there is no command like that and I haven't found another way of writing rows as columns.
推荐答案转置迭代序列的一般解决方案是:zip(*original_list)
The solution in general to transpose a sequence of iterables is: zip(*original_list)
样本输入:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15计划:
with open('in.txt') as f: lis = [x.split() for x in f] for x in zip(*lis): for y in x: print(y+' ', end='') print(' ')输出:
1 6 11 2 7 12 3 8 13 4 9 14 5 10 15更多推荐
如何在csv表中进行数据的行到列转置?
发布评论