替代 Python 2.7 之前的 dict 理解 [英] Alternative to dict comprehension prior to Python 2.7

查看:24
本文介绍了替代 Python 2.7 之前的 dict 理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

使用:

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

这是带有生成器表达式的 dict() 函数,生成 (key, value) 对.

That's the dict() function with a generator expression producing (key, value) pairs.

或者,笼统地说,形式的字典理解:

Or, to put it generically, a dict comprehension of the form:

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

总是可以与 Python 兼容

2.7 通过使用:

can always be made compatible with Python < 2.7 by using:

dict((key_expr, value_expr) for targets in iterable <additional loops or if expressions>)

这篇关于替代 Python 2.7 之前的 dict 理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆