【问题标题】:code is invalid under python 2.6 but fine in 2.7 [duplicate]代码在python 2.6下无效,但在2.7中很好[重复]
【发布时间】:2013-12-21 19:33:12
【问题描述】:

请有人帮我将一些 python 2.7 语法翻译成 python 2.6(由于 redhat 依赖关系,有点卡在 2.6 上)

所以我有一个简单的函数来构造一棵树:

def tree(): return defaultdict(tree)

当然我想以某种方式显示树。在 python 2.7 下我可以使用:

$ /usr/bin/python2.7
Python 2.7.2 (default, Oct 17 2012, 03:00:49)
[GCC 4.4.6 [TWW]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def dicts(t): return {k: dicts(t[k]) for k in t}
...
>>>

一切都好...但是在 2.6 下我收到以下错误:

$ /usr/bin/python
Python 2.6.6 (r266:84292, Sep  4 2013, 07:46:00)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def dicts(t): return {k: dicts(t[k]) for k in t}
  File "<stdin>", line 1
    def dicts(t): return {k: dicts(t[k]) for k in t}
                                           ^
SyntaxError: invalid syntax

如何重写代码:

def dicts(t): return {k: dicts(t[k]) for k in t}

以便我可以在 python 2.6 下使用它?

【问题讨论】:

    标签: python python-2.7 syntax python-2.6


    【解决方案1】:

    您必须将 dict 理解替换为 dict() 被传递一个生成器表达式。即。

    def dicts(t): return dict((k, dicts(t[k])) for k in t)
    

    【讨论】:

      【解决方案2】:
      def dicts(t):
          d = {}
          for k in t:
              d[k] = dicts(t[k])
          return d
      

      【讨论】:

        猜你喜欢
        • 2016-02-24
        • 2017-01-17
        • 2021-11-10
        • 2014-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-04
        • 2014-04-22
        相关资源
        最近更新 更多