从命令行读取输入并将其存储到二维数组中,而不是字符串inpu

2024-05-08 00:21:53 发布

您现在位置:Python中文网/ 问答频道 /正文

with open(sys.argv[1], 'r') as f:                  
    a= f.readlines()    #reads the file's lines
    a = [x.strip() for x in a] #ignores the newline char
print (a)

使用此函数,当我打印数组时,我的输出如下:

['+X..XX....-', '.X..X..X-..', '.X.........', '...XX......', 'XXX.+X.....', '..X.....XXX', '...XXX..X-.', '.-.....X...']

如何转换上述函数以使其返回

[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

类似这样的东西,一个元素数组而不是一个字符串数组


Tags: the函数aswithsys数组openfile
1条回答
网友
1楼 · 发布于 2024-05-08 00:21:53
In[3]: with open('test.txt', 'r') as f:
  ...:     result = [list(line.rstrip()) for line in f]
  ...: 
In[4]: result
Out[4]: 
[['+', 'X', '.', '.', 'X', 'X', '.', '.', '.', '.', '-'],
 ['.', 'X', '.', '.', 'X', '.', '.', 'X', '-', '.', '.'],
 ['.', 'X', '.', '.', '.', '.', '.', '.', '.', '.', '.'],
 ['.', '.', '.', 'X', 'X', '.', '.', '.', '.', '.', '.'],
 ['X', 'X', 'X', '.', '+', 'X', '.', '.', '.', '.', '.'],
 ['.', '.', 'X', '.', '.', '.', '.', '.', 'X', 'X', 'X'],
 ['.', '.', '.', 'X', 'X', 'X', '.', '.', 'X', '-', '.'],
 ['.', '-', '.', '.', '.', '.', '.', 'X', '.', '.', '.']]

相关问题 更多 >