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

时间:2018-02-14 10:55:14

标签: python arrays string multidimensional-array input

我正在尝试在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&#39 ;,' 1',' 2',' 3]',' [9',' 5', ' 1',' 2']

我想让数组与输入相同。

3 个答案:

答案 0 :(得分:3)

使用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]]

答案 1 :(得分:1)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mySelect">
    <option>Apple</option>
    <option>Pineapple</option>
    <option>Lime</option>
    <option>Pear</option>
    <option>Orange</option>
</select>

more safe

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

答案 2 :(得分:0)

请查看旧答案:

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]]