英文:
Python - how to get numbers to always print in ascending order
问题
# 这个函数比较两个数字并以升序返回它们。
def order_numbers(number1, number2):
if number2 > number1:
return number1, number2
else:
return number2, number1
smaller, bigger = order_numbers(100, 99)
print(smaller, bigger)
英文:
I am trying to write something that always prints numbers in ascending order.
I have something like this below, but it will always print the numbers in the order of which I have the variables. I know I am missing something here to make it so they will print in ascending order even if I toss in more numbers so they are always sorted. I am just not sure what to add in.
# This function compares two numbers and returns them
# in increasing order.
def order_numbers(number1, number2):
if number2 > number1:
return number1, number2
else:
return number2, number1
smaller, bigger = order_numbers(100, 99)
print(smaller, bigger)
I know I can write something like this print(sorted([smaller, bigger]))
but I don't want it to print like this [99,100]
edit1: the same goes for print(order_numbers(smaller, bigger))
答案1
得分: 1
def order_numbers(*args):
numbers = list(args)
numbers.sort()
return numbers
# the * here unpacks the list, so you don't the the square brackets of list output.
print(*order_numbers(100,21,32,12))
# 12 21 32 100
或者
print(*sorted(number_list))
英文:
def order_numbers(*args):
numbers = list(args)
numbers.sort()
return numbers
# the * here unpacks the list, so you don't the the square brackets of list output.
print(*order_numbers(100,21,32,12))
# 12 21 32 100
OR
print(*sorted(number_list))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论