gpt4 book ai didi

python - Python 2.7 之前的 dict 理解的替代方案

转载 作者:IT老高 更新时间:2023-10-28 21:54:04 26 4
gpt4 key购买 nike

如何使以下功能与 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])}

最佳答案

用途:

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

关于python - Python 2.7 之前的 dict 理解的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21069668/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com