当前位置:   article > 正文

Python 对列表进行排序_python 多维 list 排序

python 多维 list 排序

Python中,对列表进行排序有两种方法。
一种是调用 sort() 方法,该方法没有返回值,对列表本身进行升序排序。

cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
  • 1
  • 2
  • 3

输出:

['audi', 'bmw', 'subaru', 'toyota']
  • 1

另一种方法是使用 sorted() 函数,该函数会返回升序排序的列表,同时不影响原本的列表。

cars = ['bmw', 'audi', 'toyota', 'subaru']

print("Here is the original list:")
print(cars)

print("\nHere is the sorted list:")
print(sorted(cars))

print("\nHere is the original list again:")
print(cars)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

输出:

Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']

Here is the sorted list:
['audi', 'bmw', 'subaru', 'toyota']

Here is the original list again:
['bmw', 'audi', 'toyota', 'subaru']
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

参考文献:《Python编程 从入门到实践(第2版)》 埃里克 · 马瑟斯著 袁国忠译

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/723018
推荐阅读
相关标签
  

闽ICP备14008679号