Python: finding lowest integer

前端 未结 13 702
北海茫月
北海茫月 2020-12-05 18:16

I have the following code:

l = [\'-1.2\', \'0.0\', \'1\']

x = 100.0
for i in l:
    if i < x:
        x = i
print x

The code should fin

相关标签:
13条回答
  • 2020-12-05 18:45
    number_list = [99.5,1.2,-0.3]
    
    number_list.sort()
    
    print number_list[0]
    
    0 讨论(0)
  • 2020-12-05 18:46

    It looks like you want to convert the list to a list of numbers

    >>> foo = ['-1.2', '0.0', '1']
    >>> bar = map(float, foo)
    >>> bar
    [-1.2, 0.0, 1.0]
    >>> min(bar)
    -1.2
    

    or if it really is strings you want, that you want to use min's key argument

    >>> foo = ['-1.2', '0.0', '1']
    >>> min(foo, key=float)
    '-1.2'
    
    0 讨论(0)
  • 2020-12-05 18:47

    Or no float conversion at all by just specifying floats in the list.

    l = [-1.2, 0.0, 1]
    x = min(l)
    

    or

    l = min([-1.2, 0.0, 1])
    
    0 讨论(0)
  • 2020-12-05 18:49

    You have to start somewhere the correct code should be:

    The code to return the minimum value

    l = [ '0.0', '1','-1.2'] x = l[0] for i in l: if i < x: x = i print x

    But again it's good to use directly integers instead of using quotations ''

    This way!

    l = [ 0.0, 1,-1.2] x = l[0] for i in l: if i < x: x = i print x

    0 讨论(0)
  • 2020-12-05 18:53
    list1 = [10,-4,5,2,33,4,7,8,2,3,5,8,99,-34]
    
    print(list1)
    
    max_v=list1[0]
    
    min_v=list1[0]
    
    for x in list1:
        if x>max_v:
            max_v=x
            print('X is {0} and max is {1}'.format(x,max_v))
    for x in list1:
        if x<min_v:
            min_v=x
            print('X is {0} and min is {1}'.format(x,min_v))
    
    print('Max values is ' + str(max_v))
    print('Min values is ' + str(min_v))
    
    0 讨论(0)
  • 2020-12-05 18:54

    You have strings in the list and you are comparing them with the number 100.0.

    0 讨论(0)
提交回复
热议问题