Python 2.7 之前的字典理解替代方案

2024-04-29 15:11:12 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使以下功能与Python 2.7之前的Python版本兼容?

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

Tags: 功能版本sendlogcachenewdictfunc
1条回答
网友
1楼 · 发布于 2024-04-29 15:11:12

使用:

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>)

相关问题 更多 >