34

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])}
4

1 回答 1

67

利用:

gw_func_dict = dict((chr(2**i), func) for i, func in enumerate(gwfuncs[:8]))

这就是dict()生成器表达式产生(key, value)对的函数。

或者,通俗地说,是对以下形式的 dict 理解:

{key_expr: value_expr for targets in iterable <additional loops or if expressions>}

始终可以通过以下方式与 Python < 2.7 兼容:

dict((key_expr, value_expr) for targets in iterable <additional loops or if expressions>)
于 2014-01-12T00:20:45.037 回答