Python: Taking a nested list as input?

后端 未结 2 915
伪装坚强ぢ
伪装坚强ぢ 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 "<stdin>", line 1, in <module>
      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 "<unknown>", line 1
        [['', 'X', 'O'], ['X', 'O', ''], ['X', ', 'X']]
                                                   ^
    SyntaxError: invalid syntax
    
    0 讨论(0)
  • 2021-01-22 14:51

    Actually, IMHO, you can simply use json.loads and tell the user to provide a json, your program will be much more stable/usable (i.e. the user doesnt need to have prior knowledge of python but simply of json which is a standard format).

    The json corresponding to the list in question is basically almost the same as you provide (the quote should be double-quote and None should be null).

    ex

    import json
    json.loads('[["", "X", "O"], ["X", "O", ""], ["X", "", "X"]]')
    # [[u'', u'X', u'O'], [u'X', u'O', u''], [u'X', u'', u'X']]
    
    json.loads('[[null, 1, ""], [null, null, 0]]')
    # [[None, 1, u''], [None, None, 0]]
    

    If you know that you doesn't have crazy value (key with an ' inside (ex "Texas Hold'em") or key that contains None (ex "DaNone")) then you could do basic preprocessing to handle those key before hand (if you don't want to force the simple quote)

    for example:

    def parse_input_to_list(input):
        input = input.replace("'", '"').replace('None', 'null')
        return json.loads(input)
    
    
    parse_input_to_list("[['', 'X', 'O'], ['X', 'O', ''], ['X', '', 'X']]")
    # [[u'', u'X', u'O'], [u'X', u'O', u''], [u'X', u'', u'X']]  << the input you provided
    
    parse_input_to_list("[['null', 1, ''], [None, None, 0]]")
    # [[u'null', 1, u''], [None, None, 0]]
    parse_input_to_list('[[null, 1, ""], [null, null, 0]]')
    # [[None, 1, u''], [None, None, 0]]
    

    If the input provided is the output of another program then json.dumps the output of the other program for the data exchange (this is exactly for what Json is made for). and you're done.

    If there is absolutly no way of using Json then you could use the ast solution of @alsetru which does work fine.

    0 讨论(0)
提交回复
热议问题