Python – 如何让数字始终按升序打印

huangapple go评论65阅读模式
英文:

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))

huangapple
  • 本文由 发表于 2023年2月16日 05:03:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75465410.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定