• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python ast.comprehension函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中ast.comprehension函数的典型用法代码示例。如果您正苦于以下问题:Python comprehension函数的具体用法?Python comprehension怎么用?Python comprehension使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了comprehension函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_DictComp

 def test_DictComp(self):
     gen = ast.comprehension(ast.Name('x', ast.Store()), ast.Name('y',
         ast.Load()), [ast.Num(2)])
     dictcomp = ast.DictComp(ast.Name('v', ast.Load()), ast.Name('w',
         ast.Load()), [gen])
     self.verify(dictcomp, '{v:w for x in y if 2}')
     gen2 = ast.comprehension(ast.Name('a', ast.Store()), ast.Name('b',
         ast.Load()), [])
     dictcomp.generators.append(gen2)
     self.verify(dictcomp, '{v:w for x in y if 2 for a in b}')
开发者ID:DulithaRanatunga,项目名称:victims-lib-python,代码行数:10,代码来源:test_mnfy.py


示例2: seq_comp_test

 def seq_comp_test(self, node_type, ends):
     gen = ast.comprehension(ast.Name('x', ast.Store()), ast.Name('y',
         ast.Load()), [ast.Num(2)])
     listcomp = node_type(ast.Name('w', ast.Load()), [gen])
     self.verify(listcomp, '{}w for x in y if 2{}'.format(*ends))
     gen2 = ast.comprehension(ast.Name('a', ast.Store()), ast.Name('b',
         ast.Load()), [])
     listcomp.generators.append(gen2)
     self.verify(listcomp, '{}w for x in y if 2 for a in b{}'.format(*ends))
     return listcomp
开发者ID:DulithaRanatunga,项目名称:victims-lib-python,代码行数:10,代码来源:test_mnfy.py


示例3: _check_comprehension

 def _check_comprehension(self, fac):
     self.expr(fac([]), "comprehension with no generators")
     g = ast.comprehension(ast.Name("x", ast.Load()), ast.Name("x", ast.Load()), [])
     self.expr(fac([g]), "must have Store context")
     g = ast.comprehension(ast.Name("x", ast.Store()), ast.Name("x", ast.Store()), [])
     self.expr(fac([g]), "must have Load context")
     x = ast.Name("x", ast.Store())
     y = ast.Name("y", ast.Load())
     g = ast.comprehension(x, y, [None])
     self.expr(fac([g]), "None disallowed")
     g = ast.comprehension(x, y, [ast.Name("x", ast.Store())])
     self.expr(fac([g]), "must have Load context")
开发者ID:Naddiseo,项目名称:cpython,代码行数:12,代码来源:test_ast.py


示例4: parse

    def parse(self):
        """
        Convert the parsed tokens into a list of expressions then join them
        """
        self.stream = tokenise(self.source)
        steps = []
        for token in self.stream:
            code = self._token_to_code(token)
            if code:
                steps.append(code)

        # result = [str(x) for x in steps]
        return ast.Expression(
            body=ast.ListComp(
                elt=build_call(
                    ast.Name(id='str', ctx=ast.Load()),
                    args=[
                        ast.Name(id='x', ctx=ast.Load()),
                    ],
                ),
                generators=[
                    ast.comprehension(
                        target=ast.Name(id='x', ctx=ast.Store()),
                        iter=ast.List(elts=steps, ctx=ast.Load()),
                        ifs=[]
                    )
                ]
            )
        )
开发者ID:MarkusH,项目名称:rattle,代码行数:29,代码来源:template.py


示例5: For

def For(var_in, body):
    gen = [ast.comprehension(Store(n.id), s, []) for (n, s) in var_in]
    ## Nested for-loops are elided together.
    if isinstance(body, ast.GeneratorExp):
        gen.extend(body.generators)
        body = body.elt
    return ast.GeneratorExp(body, gen)
开发者ID:pombredanne,项目名称:message-db,代码行数:7,代码来源:ast.py


示例6: parse

    def parse(self):
        '''Convert the parsed tokens into a list of expressions
        Then join them'''
        steps = []
        self.stream = tokenise(self.source)
        for token in self.stream:
            code = self._token_to_code(token)
            if code is not None:
                steps.append(code)

        # result = [str(x) for x in steps]
        return ast.Module(
            body=[ast.Assign(
                targets=[ast.Name(id='result', ctx=ast.Store())],
                value=ast.ListComp(
                    elt=ast.Call(
                        func=ast.Name(id='str', ctx=ast.Load()),
                        args=[
                            ast.Name(id='x', ctx=ast.Load()),
                        ],
                        keywords=[],
                    ),
                    generators=[
                        ast.comprehension(
                            target=ast.Name(id='x', ctx=ast.Store()),
                            iter=ast.List(elts=steps, ctx=ast.Load()),
                            ifs=[]
                        )
                    ]
                )
            )
        ])
开发者ID:rapilabs,项目名称:rattle,代码行数:32,代码来源:compile.py


示例7: visit_Call

 def visit_Call(self, node):
     if node.func.id not in GRP_FUNCS:
         return node
     else:
         self.generic_visit(node)
         return ast.Call(
             func=node.func,
             args=[
                 ast.ListComp(
                     elt=node.args[0],
                     generators=[
                         ast.comprehension(
                             target=ast.Name(id="datarow", ctx=ast.Store(), lineno=0, col_offset=0),
                             iter=ast.Name(id="data", ctx=ast.Load(), lineno=0, col_offset=0),
                             ifs=[],
                             lineno=0,
                             col_offset=0
                         )
                     ],
                     lineno=0,
                     col_offset=0,
                 )
             ],
             keywords=[],
             ctx=ast.Load(),
             lineno=0,
             col_offset=0,
         )
开发者ID:cblp,项目名称:tabkit,代码行数:28,代码来源:python_fast.py


示例8: _peval_comprehension_generators

def _peval_comprehension_generators(state, generators, ctx):
    if len(generators) == 0:
        return state, []

    generator = generators[0]
    next_generators = generators[1:]

    state, iter_result = _peval_expression(state, generator.iter, ctx)

    masked_bindings = _get_masked_bindings(generator.target, ctx.bindings)
    masked_ctx = ctx.set('bindings', masked_bindings)

    state, ifs_result = _peval_comprehension_ifs(state, generator.ifs, masked_ctx)

    if is_known_value(ifs_result):
        success, bool_value = try_call(bool, args=(ifs_result.value,))
        if success and bool_value:
            ifs_result = []

    state, new_generator_kwds = map_reify(
        state, dict(target=generator.target, iter=iter_result, ifs=ifs_result))
    new_generator = ast.comprehension(**new_generator_kwds)

    state, new_generators = _peval_comprehension_generators(state, next_generators, ctx)

    return state, [new_generator] + new_generators
开发者ID:fjarri,项目名称:peval,代码行数:26,代码来源:expression.py


示例9: compile_list_comprehension

    def compile_list_comprehension(self, expr):
        # (list-comp expr (target iter) cond?)
        expr.pop(0)
        expression = expr.pop(0)
        tar_it = iter(expr.pop(0))
        targets = zip(tar_it, tar_it)

        cond = self.compile(expr.pop(0)) if expr != [] else None

        ret = ast.ListComp(
            lineno=expr.start_line,
            col_offset=expr.start_column,
            elt=self.compile(expression),
            generators=[])

        for target, iterable in targets:
            ret.generators.append(ast.comprehension(
                target=self._storeize(self.compile(target)),
                iter=self.compile(iterable),
                ifs=[]))

        if cond:
            ret.generators[-1].ifs.append(cond)

        return ret
开发者ID:koo5,项目名称:hy,代码行数:25,代码来源:compiler.py


示例10: handleComprehensions

 def handleComprehensions(self, comps, lineno, offset, *args):
     ccomps = []
 
     for c in comps:
         ccomps.append(ast.comprehension(target=self.dispatch(c.target, *args),
                                         iter=retic_ast.UseCheck(value=self.dispatch(c.iter), type=retic_ast.Subscriptable(), lineno=lineno, col_offset=offset),
                                         ifs=self.reduce(c.ifs, *args)))
     return ccomps, []
开发者ID:mvitousek,项目名称:reticulated,代码行数:8,代码来源:usage_check_inserter.py


示例11: _simple_comp

 def _simple_comp(self, fac):
     g = ast.comprehension(ast.Name("x", ast.Store()),
                           ast.Name("x", ast.Load()), [])
     self.expr(fac(ast.Name("x", ast.Store()), [g]),
               "must have Load context")
     def wrap(gens):
         return fac(ast.Name("x", ast.Store()), gens)
     self._check_comprehension(wrap)
开发者ID:timm,项目名称:timmnix,代码行数:8,代码来源:test_ast.py


示例12: visit_comp_for

    def visit_comp_for(self, values, ctx):
        """comp_for: 'for' exprlist 'in' or_test [comp_iter]"""
        if len(values) > 4:
            raise NotImplementedError("comp_for with more than 4 arguments not supported")

        node = ast.comprehension()
        node.target = self.visit(values[1], ast.Store())
        node.iter = self.visit(values[3], ctx)
        node.ifs = []
        
        return node
开发者ID:dlorch,项目名称:pycep,代码行数:11,代码来源:analyzer.py


示例13: handleComprehensions

 def handleComprehensions(self, comps, varchecks, *args):
     generators = []
     for comp in comps:
         iter = self.dispatch(comp.iter, varchecks, *args)
         target = self.dispatch(comp.target, varchecks, *args)
         
         vars = scope.WriteTargetFinder().preorder(target)
         varchecks = set.union(vars, varchecks)
         
         ifs = self.dispatch(comp.ifs, varchecks, *args)
         generators.append(ast.comprehension(target=target, iter=iter, ifs=ifs))
     return generators, varchecks
开发者ID:mvitousek,项目名称:reticulated,代码行数:12,代码来源:check_inserter.py


示例14: generate

    def generate(self, element:Element, GC:GenerationContext):


        acode = element.code

        if len(acode) is 2 and is_form(acode[1], "for"):

            for_form = acode[1].code

            # list comprehension

            # («[]» (for (in i lst) (f i))) # list compr

            in_el = for_form[1]
            in_el_code = in_el.code

            #with GC.let(domain=ExDom):

            assert is_identifier(in_el, "in")

            target_element = in_el_code[1]
            iter_element = in_el_code[2]

            with GC.let(domain=LVDom):
                target_code = GC.generate(target_element)

            with GC.let(domain=ExDom):
                iter_code = GC.generate(iter_element)



            generators = [ ast.comprehension(target=target_code,
                                             iter=iter_code,
                                             ifs=[]) ]


            to_evaluate_element = for_form[2]

            with GC.let(domain=ExDom):

                to_evaluate_code = GC.generate(to_evaluate_element)


            return ast.ListComp(to_evaluate_code, generators)


        else:

            els = self.generate_as_expressions(GC, *acode[1:])

            if GC.domain == LVDom:
                return ast.List(els, ast.Store())
            return expr_wrap(ast.List(els, ast.Load()), GC)
开发者ID:bloff,项目名称:rmtc-parsing,代码行数:53,代码来源:containers.py


示例15: p_comp_async_for2

 def p_comp_async_for2(self, p):
     ''' comp_for : ASYNC FOR exprlist IN or_test comp_iter '''
     target = p[3]
     self.set_context(target, Store, p)
     gens = []
     gens.append(ast.comprehension(target=target, iter=p[5], ifs=[],
                                   is_async=1))
     for item in p[6]:
         if isinstance(item, ast.comprehension):
             gens.append(item)
         else:
             gens[-1].ifs.append(item)
     p[0] = gens
开发者ID:nucleic,项目名称:enaml,代码行数:13,代码来源:parser36.py


示例16: test_dictcomp

    def test_dictcomp(self):
        g = ast.comprehension(ast.Name("y", ast.Store()), ast.Name("p", ast.Load()), [])
        c = ast.DictComp(ast.Name("x", ast.Store()), ast.Name("y", ast.Load()), [g])
        self.expr(c, "must have Load context")
        c = ast.DictComp(ast.Name("x", ast.Load()), ast.Name("y", ast.Store()), [g])
        self.expr(c, "must have Load context")

        def factory(comps):
            k = ast.Name("x", ast.Load())
            v = ast.Name("y", ast.Load())
            return ast.DictComp(k, v, comps)

        self._check_comprehension(factory)
开发者ID:Naddiseo,项目名称:cpython,代码行数:13,代码来源:test_ast.py


示例17: compile_expr

 def compile_expr(self, target_type):
     assert target_type is not None
     dims = self._compile_dims(target_type)
     ltype = self._lambda_type(target_type)
     
     #def array(func,dims):
     #    return [func(*d) for d in itertools.product(*(map(range,dims))]
     elt_expr = _pyast.Call(self.genexpr.compile_expr(ltype), [], [], _pyast.Name('_d', _pyast.Load()), None)                  # func(*d)
     # elt_expr = _pyast.Call(_pyast.Name('tuple', _pyast.Load()), [_pyast.Name('_d', _pyast.Load()), elt_expr], [], None, None) # tuple(d, func(*d))
     pdt_expr = _pyast.Attribute(_pyast.Name('_pyitertools', _pyast.Load()), 'product', _pyast.Load())                            # itertools.product
     itr_expr = _pyast.Call(_pyast.Name('map', _pyast.Load()), [_pyast.Name('range', _pyast.Load()), dims], [], None, None)    # map(range,dims)
     itr_expr = _pyast.Call(pdt_expr, [], [], itr_expr, None)                                                                  # itertools.product(*(map(range,dims)))
     return _pyast.ListComp(
         elt_expr,
         [_pyast.comprehension(_pyast.Name('_d', _pyast.Store()), itr_expr, [])])
开发者ID:TharinduRusira,项目名称:chill-dev,代码行数:15,代码来源:_cpp_validate_env.py


示例18: expr_Raise_Exception_string

def expr_Raise_Exception_string(message):
    # hack: (_ for _ in ()).throw(Exception(message))
    return ast.Call(
        func=ast.Attribute(
            value=ast.GeneratorExp(
                elt=ast.Name(id='_', ctx=ast.Load()),
                generators=[
                    ast.comprehension(
                        target=ast.Name(id='_', ctx=ast.Store()),
                        iter=ast.Tuple(
                            elts=[], 
                            ctx=ast.Load()), 
                        ifs=[])]), 
            attr='throw', ctx=ast.Load()),
        args=[builtin_call('Exception', [ast.Str(s=message)])],
        keywords=[],
        starargs=None,
        kwargs=None)
开发者ID:cyrus-,项目名称:typy,代码行数:18,代码来源:astx.py


示例19: enums_helper

 def enums_helper(self, enums):
     generators = []
     
     for enum in enums:
         
         if dka.hasnodetype(enum, dha.EnumFor):
             target = self.visit(enum.target)
             iter = self.visit(enum.iter)
             generators.append(ast.comprehension(target, iter, []))
         
         elif dka.hasnodetype(enum, dha.EnumIf):
             assert(len(generators) > 0)
             target = self.visit(enum.target)
             iter = self.visit(enum.iter)
             generators[-1].ifs.append(
                 ast.Compare(target, [ast.In()], [iter]))
         
         else: assert()
     
     return generators
开发者ID:sadboy,项目名称:AsdlPy,代码行数:20,代码来源:pydarkit.py


示例20: _mutual_equality_for

def _mutual_equality_for(a, b, equal):
  if len(a.elts) > len(b.elts):
    a, b = b, a
  if equal:
    op = ast.Eq()
  else:
    op = ast.NotEq()
  return ast.For(
      target=ast.Name(id='__x', ctx=_STORE),
      iter=a,
      body=[
        ast.Expr(value=ast.Compare(
            left=ast.Call(
                func=ast.Name(id='sum', ctx=_LOAD),
                args=[
                  ast.GeneratorExp(
                      elt=ast.Subscript(
                          value=ast.Name(id='__x', ctx=_LOAD),
                          slice=ast.Index(
                              value=ast.Name(id='__y', ctx=_LOAD),
                          ),
                          ctx=_LOAD,
                      ),
                      generators=[
                        ast.comprehension(
                            target=ast.Name(id='__y', ctx=_STORE),
                            iter=b,
                            ifs=[],
                            is_async=0,
                        ),
                      ],
                  ),
                ],
                keywords=[],
            ),
            ops=[op],
            comparators=[ast.Num(n=1)],
        )),
      ],
      orelse=[],
  )
开发者ID:PhilHarnish,项目名称:forge,代码行数:41,代码来源:_grammar_transformer.py



注:本文中的ast.comprehension函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python ast.copy_location函数代码示例发布时间:2022-05-24
下一篇:
Python ast.arguments函数代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap