简体   繁体   中英

Trying to shorten my python code. Does anyone have an idea?

My code works fine. I originally tried to set smallest=zero but this skipped 18. I added None. Now my code works great. However, I would like to shorten my code if there is a shorter way to write this. Does anyone have a solution? Thanks!

age = [18, 23,43,23,19,23,43,43,23,45,53,52,43,54,34,23,43]

smallest = None
for i in age:
    if smallest is None:
        smallest = i
        print(smallest)
    elif i < smallest:
        smallest = i
        print(smallest)

You could just call min()

age = [18, 23,43,23,19,23,43,43,23,45,53,52,43,54,34,23,43]
print(f"The min age is:{min(age)}")

The min age is:18

You can read more about min() here

If all you really want is the minimum number, using min() is the way to go.

If you do really want to print each smallest value so far (why??) you could combine your cases into one using or :

age = [18, 23,43,23,19,23,43,43,23,45,53,52,43,54,34,23,43]

smallest = None
for i in age:
    if smallest is None or i < smallest:
        smallest = i
        print(smallest)

It makes no difference if the first value happens to be the smallest, but if you move the 18 somewhere else in the list, it will change the output.

I can help you to make this code shorter.

My code is:

age = [18, 23,43,23,19,23,43,43,23,45,53,52,43,54,34,23,43]
age.sort()
print(age[0])

I first sorted the list in ascending order with the sort function.

Then I just printed the first element of the sorted list.

Your output is 18. My code is also giving an output of 18.

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