【问题标题】:Syntax translation from Python 2.7 to 2.6 [duplicate]从 Python 2.7 到 2.6 的语法翻译 [重复]
【发布时间】:2014-04-22 22:57:35
【问题描述】:

这是 Wagtail 中的一行代码(带有非常酷的 UI 的 Django 变体 CMS)。问题是它是为 Python 2.7 编写的,我在共享主机上使用 Python 2.6 和 Django + FastCGI。

我已经更改了之前发现的语法错误by mhlester 但无法弄清楚这一点:

>>> for attr in json_attrs
  File "<stdin>", line 1
    for attr in json_attrs
                          ^
SyntaxError: invalid syntax

原代码:

 if use_json: # Return a json response
        if search_results:
            search_results_json = []
            for result in search_results:
                result_specific = result.specific

                search_results_json.append({
                    attr: getattr(result_specific, attr)
                    for attr in json_attrs
                    if hasattr(result_specific, attr)
                })

请帮忙?

【问题讨论】:

    标签: python django python-2.7 python-2.6 wagtail


    【解决方案1】:

    tuples 中的 list 传递给 dict() 内置函数。

    dict((attr, getattr(result_specific, attr)) for attr in json_attrs if hasattr(result_specific, attr))
    

    【讨论】:

      猜你喜欢
      • 2021-09-26
      • 1970-01-01
      • 2021-01-09
      • 2017-01-17
      • 2018-08-05
      • 2012-06-24
      • 2013-11-28
      • 1970-01-01
      • 2019-06-02
      相关资源
      最近更新 更多