【问题标题】:Input two dimensional n*n array in python 2.7在 python 2.7 中输入二维 n*n 数组
【发布时间】:2018-07-24 22:07:55
【问题描述】:

我正在尝试在 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']

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

【问题讨论】:

    标签: python arrays string multidimensional-array input


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:
      exec('x=' + raw_input())
      #in x is now what you wanted, [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
      

      more safe:

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

      【讨论】:

      【解决方案3】:

      请检查一个较旧的答案:

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

      【讨论】:

        猜你喜欢
        • 2018-10-10
        • 2016-05-28
        • 2018-04-12
        • 2011-08-26
        • 1970-01-01
        • 2011-06-14
        • 2021-12-20
        • 1970-01-01
        相关资源
        最近更新 更多