python - 使用python在列中返回值而不是按行从文件中打印行
问题描述
我一定忘记了基本的python,因为在拆分它们之后我似乎无法按实际行打印行,以便每行都作为列表中的元素。
例如:
for lines in open(testfile):
print(lines.split())
输出(注意这不是列表的列表):
["The", "apple", "banana", "check"]
["Two", "apples", "three", "checks", "testest"]
["This", "is", "a", "test", "file"]
因此,如果我想自己打印第一行,我将代码更改为:
for lines in open(testfile):
print(lines.split()[0])
但是我得到了每个行列表中的第一个元素:
"The"
"Two"
"This"
但我期望:
["The", "apple", "banana", "check"]
我知道这是语法错误,我已经查过了,但我一直只得到第一个元素。抱歉,这太基础了,但我已经有一段时间没有做这样简单的事情了!
解决方案
您的for
循环将依次查看每一行,因此当您print(lines.split()[0])
执行此操作时,您一次只针对一行。您可以做的是将所有拆分的行放在自己的列表中,然后查看该列表中的第一个元素:
all_lines = [] # empty list
for line in open(testfile):
all_lines.append(line.split())
all_lines[0]
# ["The", "apple", "banana", "check"]
顺便说一句,打开文件时最好使用以下with
语句:
all_lines = []
with open(testfile) as a_file:
for line in a_file:
all_lines.append(line.split())
这里的优点是它创建了一个运行文件操作的上下文,并自动处理诸如关闭文件之类的事情。
最后,如果你只关心文件的第一行,你可以这样做:
with open(testfile) as a_file:
first_line = a_file.readline().split() # grab just the first line
first_line
# ["The", "apple", "banana", "check"]
推荐阅读
- python - 使用 Peewee ORM 按与 IN 中使用的列表相同的列表排序
- ibm-mq - 用于异步消息传递的 MQI 与 JMS / XMS
- jboss - RestEASY + Jboss 7.x - 当 Accepts 与 @Produces 值不匹配时,您可以默认使用第一个 @Path 吗?
- bokeh - 暂停/停止 AjaxDataSource 散景流
- python - 未格式化的直方图值
- css - 将 css 样式表与 express.static 问题联系起来
- python - Python:float() 参数必须是字符串或数字
- ios - 无法构建发布应用程序 - 架构 armv7 的未定义符号
- blazor - 如何使用 3.0.100 版创建 Common Blazor 组件库
- torch - 使用 torch/distro 在 Windows 10 上安装 Torch 时出现问题