python - 如何将文件的内容写入python中的列表?

标签 python python-2.7 nested-lists

我正在学习 python 编程并且被这个问题所困扰。我查看了其他示例,这些示例读取文件输入并将整个内容作为单个列表或字符串 link to that example 但我希望每一行都是一个列表(嵌套列表)我该怎么做请帮忙
文本文件为a.txt

1234 456 789 10 11 12 13

4456 585 568 2 11 13 15 

代码的输出应该是这样的

[ [1234 456 789 10 11 12 13],[4456 585 568 2 11 13 15] ]

最佳答案

没有理由执行 readlines -- 只是遍历文件。

with open('path/to/file.txt') as f:
    result = [line.split() for line in f]

如果你想要一个整数列表的列表:

with open('path/to/file.txt') as f:
    result = [map(int, line.split()) for line in f]
    # [list(map(int, line.split())) for line in f] in Python3

关于python - 如何将文件的内容写入python中的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28372562/

相关文章:

python - 用于多个客户端的扭曲服务器

python - 如何在没有 yaml.YAMLObject 的情况下执行 Python 对象的 yaml.safe_dump() 和 .safe_load()?

python - 如何将列表中的值与嵌套列表的第一个值进行比较并返回嵌套列表结果?

python - 学习算法时如何使用python?

python - 使用 Float64Index 时如何移动 DataFrame 的索引?

python - 尝试在Python中使用 docutils.parsers.rst.tableparser

python - 从一组对象 ID 中获取对象 ID

java - 将list1添加到list2并更新list1而不影响list2

html - CSS 计数器 - 递增深度嵌套列表

python - Pandoc "--filter"选项不适用于 "comments.py"脚本