max/min function on list with strings and integers
You could filter the non numeric using a generator expression:
arr = [5,3,6,"-",3,"-",4,"-"]
result = min(e for e in arr if isinstance(e, int))
print(result)
Output
3
Here's a way using directly the max
and min
built-in funtions with a custom key
:
arr = [5,3,6,"-",3,"-",4,"-"]
max(arr, key=lambda x: (isinstance(x,int), x))
# 6
And similarly for the min
:
min(arr, key=lambda x: (not isinstance(x,int), x))
# 3
Details
For the min, consider the following list comprehension as an "equivalent" of the transformation applied with the key
:
sorted([(not isinstance(x,int), x) for x in arr])
[(False, 3),
(False, 3),
(False, 4),
(False, 5),
(False, 6),
(True, '-'),
(True, '-'),
(True, '-')]
So the min
will be the lowest tuple, i.e. (0,3)
.
And for the max
, the highest will be (1,6)
:
sorted([(isinstance(x,int), x) for x in arr])
[(False, '-'),
(False, '-'),
(False, '-'),
(True, 3),
(True, 3),
(True, 4),
(True, 5),
(True, 6)]