[英]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.