Python 3.x 在Python3中如何将行转换为列?
我有一个txt文件,内容如下:Python 3.x 在Python3中如何将行转换为列?,python-3.x,Python 3.x,我有一个txt文件,内容如下: exam1 exam2 final 87 85 90 90 95 89 73 81 85 98 93 94 78 76 82 我需要这样做: [exam1',87,90,73,98,78],[exam2',85,95,81,93,76],[final',90,89,85,94,82]] 这是我的代码: f = open("score
exam1 exam2 final
87 85 90
90 95 89
73 81 85
98 93 94
78 76 82
我需要这样做:
[exam1',87,90,73,98,78],[exam2',85,95,81,93,76],[final',90,89,85,94,82]]
这是我的代码:
f = open("scores.txt", "r")
st = f.readline()
print(st)
st.split()
a = []
a = f.readline()
print(a)
我做错了什么 试试这个:
从itertools导入zip\u
以open('scores.txt','r')作为f:
content=f.read()
打印(内容)
#只打印字符串
打印(content.splitlines())
#['exam1 exam2 final','878590','909589','738185','989394','787682']
打印([c.split()表示内容中的c.splitlines()])
#[exam1]、[exam2]、[exam2]、[exam2]、[87]、[85]、[90]、[90]、[95]、[89]、[73]、[81]、[98]、[93]、[94]、[78]、[76]、[82]]
list1=[c.splitlines()中c的c.split()
#转置联机器;)
打印(列表(地图(列表,邮政编码(*list1)))
#[exam1',87',90',73',98',78'],[exam2',85',95',81',93',76'],[exam1',87',90',89',85',94',82']
#如果您有不同大小的列表,这可能更适合
打印(列表(地图(列表,邮编(*list1)))
太棒了,谢谢!如果您的列表长度相同,只需使用
zip
版本,无需导入任何内容。谢谢!我的列表长度相同,但不使用zip如何?也许是列表理解?