繁体   English   中英

在python 2.7中输入二维n * n数组

[英]Input two dimensional n*n array in python 2.7

我正在尝试在python中获取二维数组输入,该数组可以具有n个行和列。 我试过的是

x =  raw_input()[2:-2].split(',')

我的输入如下

[[1,2,3,4],[5,1,2,3],[9,5,1,2]]

我得到什么输出

['1','2','3','4]','[5','1','2','3]','[9','5','1',' 2' ]

我想获得与输入相同的数组。

使用ast.literal_eval是为此目的而设计的(这是安全的),请参见下面的代码示例中的用法:

import ast

s = '[[1,2,3,4],[5,1,2,3],[9,5,1,2]]'
ast.literal_eval(s)
# [[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]]
exec('x=' + raw_input())
#in x is now what you wanted, [[1,2,3,4],[5,1,2,3],[9,5,1,2]]

更安全

import ast
x = ast.literal_eval(raw_input())

请检查一个较旧的答案:

https://stackoverflow.com/a/21163749/2194843

$ cat /tmp/test.py

import sys, ast
inputList = ast.literal_eval(sys.argv[1])
print(type(inputList))
print(inputList)

$ python3  /tmp/test.py '[[1,2,3,4],[5,1,2,3],[9,5,1,2]]'

<class 'list'>
[[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM