python - Python 中 elif 的字典理解?

标签 python

我正在创建一个需要内部条件的字典。因此,在这里,我有一个保存一些值的 arr_temp,并且我想根据 arr_temp 中的元素设置paired_vals(现在仅适用于一种情况)。 我尝试了 if 语句,但遇到了无法在理解中使用 elif 的错误。现在我只是在各处添加 paired_vals_mass ,但这对我的情况来说是错误的,因为我有几个值来补充 arr_temp 中的每个元素。 谁能建议一个好方法来实现它?

report['conditions'][condname] = 
{findings: [{'name': x, 'parameters': paired_vals_mass} for x in arr_temp]}

最佳答案

这是在推导式中实现 elif 的方式:

a = {x: 'negative' if x < 0 else 'positive' if x > 0 else 'zero' for x in range(-2, 2)}
print(a)  # {0: 'zero', 1: 'positive', -1: 'negative', -2: 'negative'}

如您所见,没有 elif,而是嵌套的 if。即使在这种简单的情况下,代码的可读性也会降低。

更好的选择是选择器 函数,如下所示:

def selector(x):
    if x < 0:
        return 'negative'
    elif x == 0:
        return 'zero'
    else:
        return 'positive'

a = {x: selector(x) for x in range(-2, 2)}
print(a)  # {0: 'zero', 1: 'positive', -1: 'negative', -2: 'negative'}

关于python - Python 中 elif 的字典理解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45731769/

相关文章:

python - 使用 Python Selenium 获取跨度文本

python - 脚本访问 WebGoat url?

python - 无法从 csv 文件中获取前 N 个重复出现的值

python - Scrapy - 连接以非干净的方式丢失。跨单个域不一致

python - Discord.py client.say 在事件循环任务中不起作用

python - (Linux) 确定图像中不同颜色的百分比

python - 类型错误 : can't pickle generator objects wihen using mapPartitions

python - 如何修复 {"message": "The method is not allowed for the requested URL." } for my post method?

python - 重复列表创建指定形状的 numpy 数组

python - 如何在 azure 函数绑定(bind)中选择日期时间周数?