简体   繁体   中英

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.

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:

>>> 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.

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:

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 .

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.

Edit

As mentioned in the comment by Klaus , The expression is evaluated before .get() is called. 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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