有人可以帮我翻译一些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 "", 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下使用它?
你必须用dict()
传递生成器表达式来替换dict理解.即.
def dicts(t): return dict((k, dicts(t[k])) for k in t)