python中的行到列转换

2024-04-25 22:06:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个csv文件:

平均TP90
11个

10个

平均TP65平均TP80平均TP90

20 25 31个

16 19 28日

12 14 16年

11 13 16号

已用\u GB

14453年

14045年

13964个

13753年

输出应为:

平均TP90 11 10 6 平均TP65 20 16 12 11 平均TP80 25 19 14 13 平均TP90 31 28 16 16 已用\u GB 14453 14045 13964 13753

如何用python代码来实现呢?你知道吗


Tags: 文件csv代码gbtp65tp90tp80
1条回答
网友
1楼 · 发布于 2024-04-25 22:06:51

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

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)

相关问题 更多 >