Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
679 views
in Technique[技术] by (71.8m points)

list - Python: finding lowest integer

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 find the lowest value in my list (-1.2) but instead when i print 'x' it finds the value is still 100.0 Where is my code going wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To find the minimum value of a list, you might just as well use min:

x = min(float(s) for s in l) # min of a generator

Or, if you want the result as a string, rather than a float, use a key function:

x = min(l, key=float)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...