python 中使用zip实现矩阵转置

发布时间 2023-06-12 22:01:42作者: 小鲨鱼2018

 

001、

[root@PC1 test04]# ls
a.txt  test.py
[root@PC1 test04]# cat a.txt        ## 测试数据
01 02 03 04 05 06 07 08 09 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
[root@PC1 test04]# cat test.py      ## 测试程序
#!/usr/bin/env python
# -*- coding: utf-8 -*-
in_file = open("a.txt", "r")
list1 = list()
for i in in_file:
        i = i.strip().split()
        list1.append(i)
for i in list(zip(*list1)):
        i = [str(j) for j in i]
        i = " ".join(i)
        print(i)
[root@PC1 test04]# python3 test.py    ## 转置结果
01 11 21
02 12 22
03 13 23
04 14 24
05 15 25
06 16 26
07 17 27
08 18 28
09 19 29
10 20 30