python非常新。假设我有一个包含矩阵的txt文件。
matrix.txt
A A A B B C
D D C D A E
A D S A W A
现在我想将这个矩阵导入我的python程序,以便我可以处理数据。 现在的问题是我该如何追加每一行矩阵?
我尝试了什么:
file_object = open('matrix.txt', 'r')
try:
line = file_object.readline()
while line:
print line
line = file_object.readline()
line = line.strip()
string = []
string.append(line)
print string
finally:
file_object.close()
print string[0][1]
编辑:特殊情况:
A A A B B C A A A B B C
D C D A E ---> 0 D C D A E
D A W A 0 D 0 A W A
因此,如果某些元素为零,我怎样才能用0
替换它们?
答案 0 :(得分:2)
有点详尽的代码及解释:
#define a separator which divides your elements
sep = ' '
matrix = []
with open('matrix.txt', 'r') as f:
for line in f:
# generate an array with the elements which are on the line
line_array = line.split(sep)
#append it to the matrix
matrix.append(line_array)
print matrix
为了更好地理解'用'声明,阅读this,它帮助了我。
编辑: 要将双分隔符与nil(无)对象匹配,请将line_array关联替换为:
line_array = [e or 0 for e in line.split(sep)]
示例数据集(注意B和C之间的双倍空格):
A A A B C
D D C D A E
A D S A W A
编辑2: 对于平台无关的行结尾,请使用:
line_array = [e or 0 for e in line.splitlines()[0].split(sep)]
答案 1 :(得分:1)
with open('matrix.txt') as data:
matrix = [i.split() for i in data]
答案 2 :(得分:0)
您可以使用
matrix = []
for lines in open('matrix.txt', 'r'):
matrix.append(lines.split())