[英]Formatting list.sort function in Python
我有一个函数,用户在其中输入 3 个数字,它返回这 3 个数字的平均值以及按递增顺序对它们进行排序的第二行。
它目前看起来如下所示:
num1 = input('Enter your first number: ')
num2 = input('Enter your second number: ')
num3 = input('Enter your third number: ')
sum = float(num1) + float(num2) + float(num3)
avg = round(sum/3, 2)
print('The average is ' + str(avg))
list = [num1, num2, num3]
list.sort()
print('The numbers in order are {}'.format(list))
这将返回:
Enter your first number: 1
Enter your second number: 2
Enter your third number: 3
The average is 2.0
The numbers in order are ['1', '2', '3']
但是,我希望它以以下格式返回最后一行:
The numbers in order are 1, 2, 3
有没有人对能够将行格式化为我需要的功能有任何建议?
print('The numbers in order are {}'.format(', '.join(list)))
也就是说,您不应该隐藏内置list
而应该为您的变量使用不同的名称。
使用 Python f-Strings 试试这个:
print(f'The numbers in order are {", ".join(list)}')
list.sort()
list= str(list)[1:-1]
print('The numbers in order are {}'.format(list))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.