-1

I have been breaking my head with this function.

def snatch(data,threshold):

Given I have the following data:

data = { 'x': [1, 2, 3, 7], 'y': [1, 3, 7, 2] }
threshold = { 'x': 3, 'y': 2 }

Briefly, the data dictionaries' values are supposed to merge as one list, if they are above or equal to the threshold's values.

i.e. [3,7,7,3,2] for 'x' 3,7 are above or equal to threshold 'x'. And for 'y' 3,7,2 are above or equal to threshold 'y.' The mean is hence computed.

The second condition concerns the absence of a threshold. In that case, the respective letter key is excluded from the list and thus the product mean.

e.g. thresh = { 'x': 3 } hence the list from data is only [3,7]

Kash
  • 99
  • 4
  • 1
    You didn't ask a question. This isn't a discussion forum or tutorial. Please take the [tour] and take the time to read [ask] and the other links found on that page. – wwii Nov 06 '22 at 23:13
  • I apologies, I'll try harder on the next occasion and take a look at the links you've sent me. – Kash Nov 06 '22 at 23:21

2 Answers2

2

Use a list comprehension like this:

def snatch(data, threshold):
    return [v for k in threshold for v in data[k] if v >= threshold[k]]

Essentially, the function above is doing this:

def snatch(data, threshold):
    snatched = []
    for key in threshold:
        for value in data[key]:
            if value >= threshold[key]:
                snatched.append(value)
    return snatched
pythonista
  • 123
  • 1
  • 7
0

Without computing the mean, you can just iterate over the threshold items and chain the values that meet the condition. This becomes a one-liner:

from itertools import chain

def snatch(data, threshold): return list(chain(*[[a for a in data[k] if a >= v] for k, v in threshold.items()])) 

data = {'x': [1, 2, 3, 7], 'y': [1, 3, 7, 2]}
threshold = {'x': 3, 'y': 2}

print(snatch(data, threshold))
# [3, 7, 3, 7, 2]
   

And using only some of the keys gives the required result:

thresh = {'x': 3} 
print(snatch(data, thresh))
# [3, 7]
ShlomiF
  • 2,686
  • 1
  • 14
  • 19
  • `lambda` should to be assigned to variables, use `partial` or declare a "normal" function – cards Nov 06 '22 at 21:59
  • I don't think partial is relevant here. I'm using both inputs (neither of them being fixed), and `snatch` is a function, as it would be if I were to use `def`. – ShlomiF Nov 06 '22 at 22:01
  • 1
    _"For those who dislike lambda functions"_ You misunderstand. I love `lambda`s but they should be used properly. Here it is not the case – cards Nov 06 '22 at 22:04
  • Can you explain why here is not the case? – ShlomiF Nov 06 '22 at 22:05
  • https://stackoverflow.com/questions/25010167/e731-do-not-assign-a-lambda-expression-use-a-def – j1-lee Nov 06 '22 at 22:05
  • Huh. Thanks. I'll edit my answer to reflect that. – ShlomiF Nov 06 '22 at 22:07
  • 1
    Fixed. And I learned something new during the process. Thanks @cards and @j1-lee! – ShlomiF Nov 06 '22 at 22:10