如何将文件内容写入 python 中的列表?
how to write the contents of a file into lists in python?
我正在学习 python 编程并且坚持这个 problem.I 查看了其他示例,这些示例读取文件输入并将整个内容作为单个列表或字符串 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] ]
你可以做到
with open('a.txt') as f:
[[i.strip()] for i in f.readlines()]
它将打印
[['1234 456 789 10 11 12 13'], ['4456 585 568 2 11 13 15']]
注意 - 这是对您最初打印字符串问题的回答
不带引号而完全按照您的意愿打印,这是一种非常糟糕的方法
print(repr([[i.strip()] for i in f.readlines()]).replace("'",''))
这将打印
[[1234 456 789 10 11 12 13], [4456 585 568 2 11 13 15]]
lines = open('file.txt').readlines() # parse file by lines
lines = [i.strip().split(' ') for i in lines] # remove newlines, split spaces
lines = [[int(i) for i in j] for j in lines] # cast to integers
没有理由这样做 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
看起来你想要结果列表中的整数,而不是字符串;如果是:
with open(filename) as f:
result = [[int(x) for x in line.strip().split()] for line in f]
我正在学习 python 编程并且坚持这个 problem.I 查看了其他示例,这些示例读取文件输入并将整个内容作为单个列表或字符串 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] ]
你可以做到
with open('a.txt') as f:
[[i.strip()] for i in f.readlines()]
它将打印
[['1234 456 789 10 11 12 13'], ['4456 585 568 2 11 13 15']]
注意 - 这是对您最初打印字符串问题的回答
不带引号而完全按照您的意愿打印,这是一种非常糟糕的方法
print(repr([[i.strip()] for i in f.readlines()]).replace("'",''))
这将打印
[[1234 456 789 10 11 12 13], [4456 585 568 2 11 13 15]]
lines = open('file.txt').readlines() # parse file by lines
lines = [i.strip().split(' ') for i in lines] # remove newlines, split spaces
lines = [[int(i) for i in j] for j in lines] # cast to integers
没有理由这样做 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
看起来你想要结果列表中的整数,而不是字符串;如果是:
with open(filename) as f:
result = [[int(x) for x in line.strip().split()] for line in f]