如何在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 儿童毕业祝福语 简短6
14 开工仪式横幅祝福语简短
15 孩子日常祝福语大全简短
16 清晨寄语诗句祝福语简短
17 结婚送亲认亲祝福语简短
18 虎年喝酒拜年祝福语简短