如何在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 恩师诗词祝福语简短大全