在Python中,我们可以使用sort()方法或sorted()函数来对列表中的数字按升序或降序排序。下面的代码示例演示了如何对一个包含百分比的列表按降序排序。
percentages = [90, 20, 50, 70, 30]
percentages.sort(reverse=True)
print(percentages)
输出结果:
[90, 70, 50, 30, 20]
如果我们的百分比是字符串格式,我们需要将它们转换为数字,才能使用sort()方法或sorted()函数进行排序。下面是将字符串百分比转换为数字的示例:
percentages = ['90%', '20%', '50%', '70%', '30%']
percentages = [int(p.strip('%')) for p in percentages]
percentages.sort(reverse=True)
print(percentages)
输出结果:
[90, 70, 50, 30, 20]