[英]How do I turn a row into a column in Python 3?
I have a txt file that reads:我有一个txt文件,内容如下:
exam1 exam2 final
87 85 90
90 95 89
73 81 85
98 93 94
78 76 82
I need to do this:我需要这样做:
[['exam1', 87, 90, 73, 98, 78], ['exam2', 85, 95, 81, 93, 76], ['final', 90, 89, 85, 94, 82]] [['exam1', 87, 90, 73, 98, 78], ['exam2', 85, 95, 81, 93, 76], ['final', 90, 89, 85, 94, 82]]
This is the code I have:这是我的代码:
f = open("scores.txt", "r")
st = f.readline()
print(st)
st.split()
a = []
a = f.readline()
print(a)
What am I doing wrong?我究竟做错了什么?
Try this:尝试这个:
from itertools import zip_longest
with open('scores.txt', 'r') as f:
content = f.read()
print(content)
# prints just string
print(content.splitlines())
# ['exam1 exam2 final', '87 85 90', '90 95 89', '73 81 85', '98 93 94', '78 76 82']
print([c.split() for c in content.splitlines()])
# [['exam1', 'exam2', 'final'], ['87', '85', '90'], ['90', '95', '89'], ['73', '81', '85'], ['98', '93', '94'], ['78', '76', '82']]
list1 = [c.split() for c in content.splitlines()]
# transpose onliner ;)
print(list(map(list, zip(*list1))))
# [['exam1', '87', '90', '73', '98', '78'], ['exam2', '85', '95', '81', '93', '76'], ['final', '90', '89', '85', '94', '82']]
# if You have lists of different sizes this may suit better
print(list(map(list, zip_longest(*list1))))
https://docs.python.org/3.6/library/itertools.html#itertools.zip_longest https://docs.python.org/3.6/library/itertools.html#itertools.zip_longest
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.