如何在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 生女孩红包简短祝福语