Find maximum int value from list which contain both str and int python

旧街凉风 提交于 2019-12-17 20:43:03

问题


Looking to find max from the combine list as follows:

['filename1', 1696, 'filename2', 5809,....]

I have tried following:

max(['filename1', 1696, 'filename2', 5809,....])

that return me TypeError: '>' not supported between instances of 'int' and 'str'. Any suggestion would help. What I want is to find the max integer value from the list above mentioned.


回答1:


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



回答2:


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).




回答3:


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))



回答4:


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



回答5:


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)])


来源:https://stackoverflow.com/questions/50037992/find-maximum-int-value-from-list-which-contain-both-str-and-int-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!