如何在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 教师闺蜜祝福语简短