我有一个1和0的块,用字符串:
1111110000111111
1110110110110111
1101010110101011
1011100110011101
0001111111111011
1000110111110111
0100010011110000
0110000001111110
0111000000110110
0000100010010100
1110110011000111
1101111111100011
1011100110000011
1101010111100001
1110110110111101
1111110000111111
我想转置它,好像它是一个矩阵 - 但是把它保存在字符串中。
在我开始编写嵌套for循环之前,有更简单的方法吗?
答案 0 :(得分:6)
s = """1111110000111111
1110110110110111
1101010110101011
1011100110011101
0001111111111011
1000110111110111
0100010011110000
0110000001111110
0111000000110110
0000100010010100
1110110011000111
1101111111100011
1011100110000011
1101010111100001
1110110110111101
1111110000111111"""
>>> [''.join(i) for i in zip(*s.split())]
['1111010000111111',
'1110001110110111',
'1101000110101011',
'1011100010011101',
'1101110001111011',
'1110111000110111',
'0000100000010000',
'0111110000011110',
'0111111001111110',
'0000111100110100',
'1110111110010111',
'1101111111000011',
'1011100100000011',
'1101010111100011',
'1110110110111001',
'1111110000111111']
修改强>
如果您确实需要一个字符串作为输出,请再添加一个join
>>> '\n'.join(''.join(i) for i in zip(*s.split()))
'1111010000111111\n1110001110110111\n1101000110101011\n1011100010011101\n1101110001111011\n1110111000110111\n0000100000010000\n0111110000011110\n0111111001111110\n0000111100110100\n1110111110010111\n1101111111000011\n1011100100000011\n1101010111100011\n1110110110111001\n1111110000111111'