【问题标题】:Alternative to dict comprehension prior to Python 2.7Python 2.7 之前的 dict 理解的替代方案
【发布时间】:2014-01-30 22:08:35
【问题描述】:

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

【问题讨论】:

    标签: python dictionary python-2.x python-2.6 dictionary-comprehension


    【解决方案1】:

    用途:

    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

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

    【讨论】:

    • 我猜第二个兼容Python=2.7?如果不是,我通常会使用 try 为两者获得一个健壮的版本,但我认为我无法捕捉到语法错误。
    • @Kvothe 此答案中的语法是前向兼容的,适用于 Python 2.4 及更高版本(包括所有 Python 3.x 版本)。
    猜你喜欢
    • 2020-08-29
    • 2020-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多