如何在Python中生成排序列表?
python中列表上的sort方法使用给定类的gt和lt运算符进行比较。大多数内置类已经实现了这些运算符,因此它将自动为您提供排序列表。您可以按以下方式使用它:
words = ["Hello", "World", "Foo", "Bar", "Nope"] numbers = [100, 12, 52, 354, 25] words.sort() numbers.sort() print(words) print(numbers)
这将给出输出:
['Bar', 'Foo', 'Hello', 'Nope', 'World'] [12, 25, 52, 100, 354]
如果您不希望对输入列表进行排序,则可以使用sorted函数进行排序。例如,
words = ["Hello", "World", "Foo", "Bar", "Nope"] sorted_words = sorted(words) print(words) print(sorted_words)
这将给出输出:
["Hello", "World", "Foo", "Bar", "Nope"] ['Bar', 'Foo', 'Hello', 'Nope', 'World']
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短