简体   繁体   English

如何在 Python 3 中将一行变成一列?

[英]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.

相关问题 如何从 Python 中的 3 行矩阵中过滤行和列? - How do i filter row and column from a 3 row matrix in Python? 如何根据 python 中的行值生成 id 列? - How do I generate id column based on row values in python? 如何在python中使用PIL直接将像素数组转换为图像? - How do I directly turn an array of pixels into an image with PIL in python? 我想根据行和列的位置重新排列一个数组,在 Python 怎么办? - I want to rearrange an array according to row and column positions, how can I do it in Python? 如何将第一行变成一列,并使它仍然与它的多个值对齐? - How can I turn the first row into a column and have it still line up with its multiple values? Python - Openpyexcel - 条件格式,到底如何将规则应用于列,但突出显示该行? - Python - Openpyexcel - Conditional formatting, How on earth do i apply the rule to a column, but highlight the row? 如何在我的数据框中添加一列,说明每一行来自哪个工作表名称? Python - How do I add a column to my dataframe that says what sheet name each row is from? Python 如何将今天的日期放在 Python 数据框中每一行的第一列? - How do I put today's date in the first column of every row in Python's dataframe? 我如何使用 python 检索熊猫分组的最后一列行值? - How do i use python to retrieve the last column row value for a pandas group-by? 如何将 Python 程序转换为 CLI 而无需键入 python3 来执行? - How do I turn a Python program into a CLI without having to type python3 to execute?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM