Python: finding lowest integer

前端 未结 13 761
北海茫月
北海茫月 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:31

    l is a list of strings. When you put numbers between single quotes like that, you are creating strings, which are just a sequence of characters. To make your code work properly, you would have to do this:

    l = [-1.2, 0.0, 1]  # no quotation marks
    
    x = 100.0
    for i in l:
        if i < x:
            x = i
    print x
    

    If you must use a list of strings, you can try to let Python try to make a number out of each string. This is similar to Justin's answer, except it understands floating-point (decimal) numbers correctly.

    l = ['-1.2', '0.0', '1']
    
    x = 100.0
    for i in l:
        inum = float(i)
        if inum < x:
            x = inum
    print x
    

    I hope that this is code that you are writing to learn either Python or programming in general. If this is the case, great. However, if this is production code, consider using Python's built-in functions.

    l = ['-1.2', '0.0', '1']
    lnums = map(float, l)  # turn strings to numbers
    x = min(lnums)  # find minimum value
    print x
    

提交回复
热议问题