29
如何使以下功能與Python 2.7以前版本的Python兼容?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])}
如何使以下功能與Python 2.7以前版本的Python兼容?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)
對。
或者,把它統稱爲形式的字典理解:
{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>)