Вопрос

I am trying to parse lisp input to python list. But when I parse the input I get list of strings but I want individual element as int.

Example: When I parse following input: "(2 (10 (5 11))) (5 6) (4)" Output: [[['2'], ['10', '5']], [['5'], ['6']], [['4']]]

I use: [[map(int, x) for x in lst] for lst in test] to convert the strings to int but this function will only parse nested list of level 2. But if I have a nested list of more than 2, how should I use it to parse?

I tried pyparsing but I didn't understand it properly.

Это было полезно?

Решение 2

If you want to use pyparsing, you could do so without any postprocessing as follows.

import pyparsing as pp

integer = pp.Word(pp.nums).setParseAction(lambda m:int(m[0]))
expr = pp.Forward()
expr << pp.nestedExpr(content=pp.OneOrMore(integer | expr))
manyExpr = pp.OneOrMore(expr)

print manyExpr.parseString('(2 (10 (5 11))) (5 6) (4)')
    #returns [[2, [10, [5, 11]]], [5, 6], [4]]

This first defines an integer as something consisting only of numbers, and tells pyparsing how to convert it from a string of numbers to an integer object. Next, it makes defines an expression as a list of expressions or integers inside parentheses. Finally, in order to parse your example, it looks for many consecutive expressions.

Другие советы

def as_int(xs):
    if isinstance(xs, list):
        return map(as_int, xs)
    elif isinstance(xs, str):
        return int(xs)
    return xs

Usage:

>>> xs = [[['2'], ['10', '5']], [['5'], ['6']], [['4']]]
>>> print as_int(xs)
[[[2], [10, 5]], [[5], [6]], [[4]]]
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top