Python 如何将字符串文件导入列表列表?
基本上我有一个文本文件:Python 如何将字符串文件导入列表列表?,python,list,file-io,python-3.3,Python,List,File Io,Python 3.3,基本上我有一个文本文件: -1 2 0 0 0 0 0 2 -1 -1 -2 0 0 -2 2 0 1 0 我想把它放在一个列表中,这样看起来: [[-1,2,0],[0,0,0],[0,2,-1],[-1,-2,0],[0,-2,2],[0,1,0]] 到目前为止,我已经有了这段代码,但它在列表中生成了一个字符串列表 import os f = open(os.path.expanduser("~/Desktop/example
-1 2 0
0 0 0
0 2 -1
-1 -2 0
0 -2 2
0 1 0
我想把它放在一个列表中,这样看起来:
[[-1,2,0],[0,0,0],[0,2,-1],[-1,-2,0],[0,-2,2],[0,1,0]]
到目前为止,我已经有了这段代码,但它在列表中生成了一个字符串列表
import os
f = open(os.path.expanduser("~/Desktop/example board.txt"))
for line in f:
for i in line:
line = line.strip()
line = line.replace(' ',',')
line = line.replace(',,',',')
print(i)
print(line)
b.append([line])
产生['-1,2,0'],['0,0,0'],['0,2,-1'],['-1,-2,0'],['0,-2,2'],['0,1,0']
这几乎就是我想要的,除了引号。使用模块:
我建议只使用numpy,而不是重新发明轮子
>>> import numpy as np
>>> np.loadtxt('example board.txt', dtype=int).tolist()
[[-1, 2, 0], [0, 0, 0], [0, 2, -1], [-1, -2, 0], [0, -2, 2], [0, 1, 0]]
注意:根据您的需要,您可能会发现numpy数组是比列表更有用的数据结构。这应该可以做到,因为您似乎希望数据是数字而不是字符串:
fin = open('example.txt','r')
# The list we want
list_list = []
for line in fin:
# Split the numbers that are separated by a space. Remove the CR+LF.
numbers = line.replace("\n","").split(" ")
# The first list
list1 = []
for digit in numbers:
list1.append(int(digit))
# The list within the list
list_list.append(list1)
fin.close()
这将产生如下输出:
[[-1, 2, 0], [0, 0, 0], [0, 2, -1], [-1, -2, 0], [0, -2, 2], [0, 1, 0]]
没有附加库的简单解决方案
import os
lines = []
f = open(os.path.expanduser("~/Desktop/example board.txt"))
for line in f:
x = [int(s) for s in line.split()]
lines.append(x)
输出:
[[-1, 2, 0], [0, 0, 0], [0, 2, -1], [-1, -2, 0], [0, -2, 2], [0, 1, 0]]
如果您有逗号分隔的值,则模块通常是您的最佳选择。如果这不是一个很好的匹配,无论出于什么原因,那么这里有一种方法,只使用内置的字符串和列表 您可以在列表中完成整个操作:
with open('~/Desktop/example board.txt', 'r') as fin:
lines = [[int(column.strip()) for column in row.split(',')] for row in fin]
但这是不透明的,可以进行重构:
def split_fields(row):
fields = row.split(',')
return [int(field.strip()) for field in fields]
with open('~/Desktop/example board.txt', 'r') as fin:
lines = [split_fields(row) for row in fin]
你打印的东西看起来像一个列表,但实际上你并没有创建一个列表。这是预期的行为吗?不,我希望它的行为像列表一样。在我的程序的下一部分中,我需要引用列表中的每个元素。您仍然需要将每个字段中的值转换为整数。@BurhanKhalid+1我删除了我的元素以支持这一点(但是您应该在Python 3中提到,您希望使用
open('data',newline='')
由于OP可能使用Py 3。同样以二进制读取模式打开我在Mac上使用的是Python 3.3.0,如果这增加了一些清晰度的话,我认为这可能会对多个空格造成一些困难。实际上,我认为文件可能是以制表符分隔的。当我尝试导入numpy时,它会给出错误:ImportError:没有名为'numpy'的模块,因为它不包含在内用python本机编写。但别让它吓跑你,安装它吧!我实际上比我更喜欢这一个。+1很好,但你应该使用with语句。open(“~/Desktop/example board.txt”)
成功了--您不需要os.path.expanduser吗?
?谢谢!这正是我需要的,我需要多练习一下列表理解。我确实需要导入操作系统并使用os.path.expanduser
def split_fields(row):
fields = row.split(',')
return [int(field.strip()) for field in fields]
with open('~/Desktop/example board.txt', 'r') as fin:
lines = [split_fields(row) for row in fin]