Friday 15 January 2010

Python: Taking a nested list as input? -



Python: Taking a nested list as input? -

what best way go following?

i want allow user input nested list follows:

grid = input('enter grid')

the user inputting grid such this:

[['', 'x', 'o'], ['x', 'o', ''], ['x', '', 'x']]

the problem passing input function expecting input nested list. when getting input grid going string not work function. if type convert grid list using list() produces list every charter of grid, i.e [,[,','.

what way take input in form above , turn nested list passed function? want input value nested list if set programme itself.

thanks

as inspectorg4dget commented, utilize 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, grab syntaxerror:

>>> ast.literal_eval("[['', 'x', 'o'], ['x', 'o', ''], ['x', ', 'x']]") traceback (most recent phone 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 homecoming compile(source, filename, mode, pycf_only_ast) file "<unknown>", line 1 [['', 'x', 'o'], ['x', 'o', ''], ['x', ', 'x']] ^ syntaxerror: invalid syntax

python python-3.x

No comments:

Post a Comment