Python 2.7 之前字典推导的替代方案
- 2025-02-14 09:50:00
- admin 原创
- 41
问题描述:
如何使以下功能与 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])}
解决方案 1:
使用:
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>)
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD