Reputation: 573
I have this function below which makes object instances as list,
lst = []
class Ppl:
def __init__(self, pid):
# local variables
self.pid = pid
self.pos = [3*pid, 10+pid-4*pid, 5*pid]
for index in range(3):
lst.append(Ppl(index))
for index in range(len(lst)):
print(lst[index].pos)
The above will output.
[0, 10, 0]
[3, 7, 5]
[6, 4, 10]
now I want to make a comprehension list based on the above lists to get the minimum values excluding zero.. so that the expected output is
[3, 4, 5]
I have this function below which works but it includes 0.
lst2 = list(map(min, *[x.pos for x in lst]))
print(lst2)
>> [0, 4, 0]
So is there a way to improve the above code or is there a better solution ?
Upvotes: 1
Views: 1746
Reputation: 8500
If you are restricted to use one-liner, here is possible solution:
lst2 = list(map(lambda *args: min(arg for arg in args if arg != 0), *[x.pos for x in lst]))
min
replaced with a lambda that applies min
after filtering zero values.
Upvotes: 1
Reputation: 593
Try the below code snippet.
import numpy as np
lst2 = np.array([x.pos for x in lst])
lst2[lst2==0]=np.max(lst2)
print(np.min(lst2,axis=0))
Output: [3 4 5]
Upvotes: 1
Reputation: 43169
You could easily define yourself a function for this:
def min2(iterator, threshold = 0):
minvalue = None
for x in iterator:
if (x > threshold) and (x < minvalue or minvalue is None):
minvalue = x
return minvalue
Test it with some asserts:
assert min2([0, 10, 0]) == 10
assert min2([3, 7, 5]) == 3
assert min2([6, 4, 10]) == 4
assert min2([10, 10, 101], threshold=100) == 101
Upvotes: 1