Python中sort和sorted的区别

  • sort

  • a = [1, 2, -5, 6, 7]

  • a.sort(reverse=True)

  • 输出:a : [7, 6, 2, 1, -5]

  • sorted:

  • a = [1, 2, -5, 6, 7]

  • b = sorted(a, reverse=True)

  • 输出b:[7, 6, 2, 1, -5]

  • 输出a:[1, 2, -5, 6, 7]

  • 总结:sort方法和sorted方法大致用法,但是sort方法会导致list本身数据结构的变化,sorted在使用时会把之前的数据copy一份,在copy的那份进行排序

评论