简体   繁体   中英

Find lowest integer in list, which has both strings and integers

I want to find the lowest integer in a list, which contains strings and integers. Is there a quick way to find it?

I could solve the issue with regex. But that sounds too much work for this. Create a new list, with list comprehension sounds better. But isn't there an easier way?

my_list = [2, 4, 'foo']

of course min(my_list) won't work because of the string inside.

You can use a generator expression to filter out non-ints:

min(n for n in my_list if isinstance(n, int))
# returns 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM