Python: Taking a nested list as input?

后端 未结 2 919
伪装坚强ぢ
伪装坚强ぢ 2021-01-22 14:23

What is the best way to go about the following?

I want to let a user input a nested list as follows:

grid = input(\'Enter grid\')

The

2条回答
  •  执笔经年
    2021-01-22 14:50

    As inspectorG4dget commented, use ast.literal_eval:

    >>> import ast
    >>> ast.literal_eval("[['', 'X', 'O'], ['X', 'O', ''], ['X', '', 'X']]")
    [['', 'X', 'O'], ['X', 'O', ''], ['X', '', 'X']]
    

    To filter out invalid input, catch SyntaxError:

    >>> ast.literal_eval("[['', 'X', 'O'], ['X', 'O', ''], ['X', ', 'X']]")
    Traceback (most recent call last):
      File "", line 1, in 
      File "/usr/lib/python3.4/ast.py", line 46, in literal_eval
        node_or_string = parse(node_or_string, mode='eval')
      File "/usr/lib/python3.4/ast.py", line 35, in parse
        return compile(source, filename, mode, PyCF_ONLY_AST)
      File "", line 1
        [['', 'X', 'O'], ['X', 'O', ''], ['X', ', 'X']]
                                                   ^
    SyntaxError: invalid syntax
    

提交回复
热议问题