替代Python之前的语法理解2.7 [英] Alternative to dict comprehension prior to Python 2.7
本文介绍了替代Python之前的语法理解2.7的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使以下功能与Python 2.7之前的版本兼容?
How can I make the following functionality compatible with versions of Python earlier than Python 2.7?
gwfuncs = [reboot, flush_macs, flush_cache, new_gw, revert_gw, send_log]
gw_func_dict = {chr(2**i): func for i, func in enumerate(gwfuncs[:8])}
推荐答案
使用:
gw_func_dict = dict((chr(2**i), func) for i, func in enumerate(gwfuncs[:8]))
这是 dict()
函数,一个生成器表达式生成(key,value)
对。
That's the dict()
function with a generator expression producing (key, value)
pairs.
或者,一般来说,对形式的字母理解:
Or, to put it generically, a dict comprehension of the form:
{key_expr: value_expr for targets in iterable <additional loops or if expressions>}
始终可以与Python兼容2.7通过使用:
can always be made compatible with Python < 2.7 by using:
dict((key_expr, value_expr) for targets in iterable <additional loops or if expressions>)
这篇关于替代Python之前的语法理解2.7的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文