python

时间:2017-01-31 07:41:31

标签: python

我有一个像这样的csv文件:

AVG_TP90
11

10

6

6

AVG_TP65 AVG_TP80 AVG_TP90

20 25 31

16 19 28

12 14 16

11 13 16

USED_GB

14453

14045

13964

13753

输出应为:

AVG_TP90 11 10 6 6 AVG_TP65 20 16 12 11 AVG_TP80 25 19 14 13 AVG_TP90 31 28 16 16 USED​​_GB 14453 14045 13964 13753

如何通过python代码完成?

1 个答案:

答案 0 :(得分:0)

您可以阅读内容,找出尺寸,然后进行转置:

with open("x.txt", "r") as infile:
    # Read line by line and split by space already 
    x = [[k for k in j.split()] for j in [i.strip("\n") for i in infile if i != "\n"]]
cols, rows = max([len(i) for i in x]), len(x) # Get dimensions
output = []
# Transpose, swap rows and columns
for i in range(cols):
    for j in range(rows):
        try:
            output.append(x[j][i])
        except IndexError:
            pass
# Construct the desired output string
retstr = ""
for i in output:
    retstr += i+" "
print(retstr)