在List Comprehension中将dict.get用于if elif和else

时间:2019-12-27 10:26:07

标签: python dictionary if-statement conditional-statements list-comprehension

我想在列表理解中实现if elifelse,在this stackoverflow答案中,我找到了一种方法。

所以让我解释一下问题是什么

根据答案,dict.get()可以按以下方式用于在列表理解中使用条件:

>>> l = [1, 2, 3, 4, 5]
>>> d = {1: 'yes', 2: 'no'}
>>> [d.get(x, 'idle') for x in l]
['yes', 'no', 'idle', 'idle', 'idle']

似乎很好。但是我遇到了另一种问题。 因此,我需要使用相同的方法来处理其他列表的索引。请允许我解释一下:

perc = np.array([0, 0.25, 0.5, 0.75, 1])

d= {0: 0, len(perc):1}

result = [d.get(x, (perc[x-1]+perc[x])/2) for x in range(len(perc)+1)]

所以简而言之,我希望我的输出为0和1,因为x为0和len(perc),或者是先前值和当前值的平均值。

现在,这给了我一个错误:

IndexError: index 5 is out of bounds for axis 0 with size 5

我的问题是,不是dict.get(key[, default])定义为:

  

如果key在字典中,则返回key的值,否则返回默认值。如果未指定default,则默认为None,因此此方法永远不会引发KeyError

现在显然在字典中将5作为键是len(perc)=5,然后为什么要首先检查默认条件,这显然会产生错误,因为数组perc中没有5th索引

编辑

Klaus的注释中所述,在调用.get()之前对表达式求值。如果是这种情况,对此无能为力,那么还有其他方法可以实现而无需使用循环吗?

1 个答案:

答案 0 :(得分:1)

你想要这样吗?

import numpy as np
perc = np.array([0, 0.25, 0.5, 0.75, 1])
d= {0: 0, len(perc):1}
result = [d.get(x, (lambda y: ((perc[y-1]+perc[y])/2) if y < len(perc) else 99999)(x)) for x in range(len(perc)+8)]
print(result)
#[0, 0.125, 0.375, 0.625, 0.875, 1, 99999, 99999, 99999, 99999, 99999, 99999, 99999]
相关问题