【问题标题】:How to find list comprehension in python code如何在python代码中找到列表理解
【发布时间】:2016-05-11 01:08:48
【问题描述】:

我想在 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

使用正则表达式的解决方案也是有效的。

谢谢

【问题讨论】:

  • 你能假设源代码中的所有列表推导在语法上都是正确的吗?

标签: python list-comprehension pygments


【解决方案1】:

您可以使用 ast 库将 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

【讨论】:

    【解决方案2】:

    您可以使用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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 2020-12-03
      • 2020-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多