简体   繁体   English

在 List Comprehension 中为 if elif 和 else 使用 dict.get

[英]Making use of dict.get for if elif and else in List Comprehension

I wanted to implement if elif and else inside a list comprehension and in this stackoverflow answer I found a way of doing the same.我想在列表理解中实现if elifelse ,在这个stackoverflow 答案中,我找到了一种方法。

So let me explain what the issue is:那么让我解释一下这个问题是什么:

As per the answer, the dict.get() can be used in following way to use conditionals in list comprehension:根据答案,可以通过以下方式使用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']

Seems nice and good.看起来不错不错。 But I am running into a different kind of problem.但我遇到了另一种问题。 So I need to use the same method to work with the index of some other list.所以我需要使用相同的方法来处理其他一些列表的索引。 Allow me to explain:请允许我解释一下:

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

So in short I want my output to be 0 and 1 for x being 0 and len(perc), or else average of previous value and current value.所以简而言之,我希望我的输出为 0 和 1,因为 x 是 0 和 len(perc),或者是先前值和当前值的平均值。

Now, this is giving me an error:现在,这给了我一个错误:

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

My question is, wasn't dict.get(key[, default]) defined as:我的问题是,不是dict.get(key[, default])定义为:

Return the value for key if key is in the dictionary, else default.如果键在字典中,则返回键的值,否则返回默认值。 If default is not given, it defaults to None, so that this method never raises a KeyError .如果未给出默认值,则默认为 None,因此此方法永远不会引发KeyError

Now clearly 5 as a key is in the dictionary as len(perc)=5 , then why the default condition is being checked first, which obviously will give an error as there is no 5th index in the array perc.现在显然 5 作为键在字典中作为len(perc)=5 ,那么为什么首先检查默认条件,这显然会产生错误,因为数组 perc 中没有5th索引。

Edit编辑

As mentioned in the comment by Klaus , The expression is evaluated before .get() is called.正如Klaus在评论中提到的,在调用 .get() 之前评估表达式。 If that's the case and nothing can be done about this, then is there any other way I can achieve this without using loops?如果是这种情况并且对此无能为力,那么有没有其他方法可以在不使用循环的情况下实现这一目标?

do you want like this?你想要这样吗?

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM