如何在python-cod中找到列表理解

2024-04-29 10:34:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在python源代码中找到一个列表理解,为此我尝试使用Pygments,但它没有找到实现的方法。在

更具体地说,我想做一个函数来识别所有可能的列表理解。例如:

[x**2 for x in range(5)]

[x for x in vec if x >= 0]

[num for elem in vec for num in elem]

[str(round(pi, i)) for i in range(1, 6)]

这个例子来自https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions

对于正则表达式的解也是有效的。在

谢谢你


Tags: 方法函数in列表forif源代码pygments
2条回答

您可以使用^{}库将Python代码解析为语法树,然后遍历解析后的树来查找ListComp表达式。在

下面是一个简单的示例,它打印出在通过stdin传递的Python代码中找到列表理解的行号:

import ast
import sys

prog = ast.parse(sys.stdin.read())
listComps = (node for node in ast.walk(prog) if type(node) is ast.ListComp)
for comp in listComps:
    print "List comprehension at line %d" % comp.lineno

您可以使用ast模块。在

import ast

my_code = """
print "Hello"
y = [x ** 2 for x in xrange(30)]
"""

module = ast.parse(my_code)
for node in ast.walk(module):
    if type(node) == ast.ListComp:
        print node.lineno  # 3
        print node.col_offset  # 5
        print node.elt  # <_ast.BinOp object at 0x0000000002326EF0>

相关问题 更多 >