美文网首页
【Python】sorted 函数

【Python】sorted 函数

作者: 盐果儿 | 来源:发表于2023-05-05 18:13 被阅读0次

    # sort a list of integers in ascending order

    numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

    sorted_numbers = sorted(numbers)

    print(sorted_numbers)  # [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

    # sort a list of strings in reverse order

    fruits = ["apple", "banana", "orange", "kiwi", "mango"]

    sorted_fruits = sorted(fruits, reverse=True)

    print(sorted_fruits)  # ["orange", "mango", "kiwi", "banana", "apple"]

    # sort a list of tuples based on the second element

    students = [("Alice", 20), ("Bob", 19), ("Charlie", 21), ("Dave", 18)]

    sorted_students = sorted(students, key=lambda x: x[1])

    print(sorted_students)  # [("Dave", 18), ("Bob", 19), ("Alice", 20), ("Charlie", 21)]

    相关文章

      网友评论

          本文标题:【Python】sorted 函数

          本文链接:https://www.haomeiwen.com/subject/zrdqsdtx.html