Print the minimum number of the list?

1

I have this code and I can not get the number -1 shown. Give an error:

  

Not supported between instances of 'str' and 'int'.

From what I've seen from other forums there is a comparison of strings with integers. How can I overcome this?

list1=[2,2, 'a', 31, int(-1), 'b']
list2=[1, 3, 40]
list1[len(list1):]=list2
list1.append(5)

print (len(list1))
print (sorted (list1[7:]))
print (min(list1))

print (list1)
    
asked by anonymous 10.04.2017 / 17:29

2 answers

3

I think the best way is to ignore not a number .

This is because if the smaller number has a floating point the other proposed solution will ignore it.

In Python3 this is very easy

import numbers
min([x for x in list1 if isinstance(x, numbers.Number)])

Take this test

list1=[2, 2, 'a', 31, int(-1), 'b']
list2=[1, 3, 40]
list1[len(list1):] = list2
list1.append(5)
list1.append(-3.0)

min([x for x in list1 if isinstance(x, numbers.Number)])
# Saída: -3.0

min(filter(lambda x: isinstance(x, int), list1))
# Saída: -1
    
10.04.2017 / 18:18
2

Use filter to remove non-integer values from your list :

list1 = [1, 2, 3, 'b']

result = min(filter(lambda x: isinstance(x, int), list1))

print(result)

The function filter will return all items in the list by evaluating the callback passed, if the sentence is true.

That is:

lambda x: isinstance(x, int)
    
10.04.2017 / 17:38