Skip to content Skip to sidebar Skip to footer

Alternative Solution Not Using Closures

I have a class Data which I want to filter using the below api. # Example: filter using where inpt = {'a':np.array((1,2,3,4,2,5,6,2,3,3,2,1)), 'b':np.random.rand(12)} dat

Solution 1:

I don't really understand the point. Maybe if you give an example of what you're actually trying to do?

If you already know the right key, you can just check directly. If you want to find the right key, the pythonic way is to use a list comprehension.

In [2]: inpt = {
   ...:     "a": (1,2,3,4,2,5,6,2,3,3,2,1),
   ...:     "b": 3,
   ...: }

In [3]: inpt["a"] == 3
Out[3]: False

In [4]: inpt["b"] == 3
Out[4]: True

In [5]: [key for key, value in inpt.items() if value == 3][0]
Out[5]: 'b'

In [8]: from typing import Sequence

In [9]: [key for key, value in inpt.items() if isinstance(value, Sequence) and 3 in value][0]
Out[9]: 'a'

Post a Comment for "Alternative Solution Not Using Closures"