Looking to find max
from the combine list as follows:
[\'filename1\', 1696, \'filename2\', 5809,....]
I have tried following:<
The same isinstance idea can be applied to a filter:
f = ['filename1', 1696, 'filename2', 5809]
max(filter(lambda i: isinstance(i, int), f))
Also, if you need to include more than one data type in your comparison, e.g.: floats, you can simple use a tuple to validate the the data to be compared:
max(filter(lambda i: isinstance(i, (int, float)), f))
If your real data also has alternating strings and integers, like your example, you can just iterate in steps of size 2, starting with the second element:
values = ['filename1', 1696, 'filename2', 5809, ...]
max(values[1::2])
# 5809
Note that this slicing creates a new list (so depending on the size of the original list it might be very large).
Use list comprehension
with isinstance
to extract the int
and then use max
.
Ex:
f = ['filename1', 1696, 'filename2', 5809]
print(max([i for i in f if isinstance(i, int)]))
#or generator
print(max((i for i in f if isinstance(i, int)))) #Better Option
Output:
5809
5809
You can also use try...except
clause.
lst = ['filename1', 1696, 'filename2', 5809]
numbers = []
for item in lst:
try:
numbers.append(int(item))
except ValueError:
pass # Ignore items which are not numbers
print(max(numbers))
# 5809
max()
expects iterable with comparable values. You should ignore string first from the list and then use max()
on it.
Use list comprehension to only consider integer values
file_data = ['filename1', 1696, 'filename2', 5809,....]
max([elem for elem in file_data if isinstance(elem, int)])
If you are expecting float values as well, you can update it as:
max([elem for elem in file_data if not isinstance(elem, str)])