我知道
如标题所述,我想比较list.sort()和sorted(list)。上面的片段显示了一个有趣的事实,Python的sort函数对已经排序的数据表现非常好。正如Anurag所指出的,在第一个情况中,sort方法处理的是已经排序的数据,而在第二个情况中,sorted方法在新的数据上工作,需要重复进行排序。
__builtin__
sorted()函数适用于任何可迭代对象。但是有人能解释一下为什么anylist.sort()和sorted(anylist)之间会有这么大(10倍)的性能差异吗?如果我测量的方式有误,请指出来。
""" 示例输出: $ python list_sort_timeit.py 使用sort方法:20.0662879944 使用排序内置方法:259.009809017 """
import random import timeit print '使用sort方法:', x = min(timeit.Timer("test_list1.sort()", "import random;test_list1=random.sample(xrange(1000),1000)").repeat()) print x print '使用排序内置方法:', x = min(timeit.Timer("sorted(test_list2)", "import random;test_list2=random.sample(xrange(1000),1000)").repeat()) print x
如标题所述,我想比较list.sort()和sorted(list)。上面的片段显示了一个有趣的事实,Python的sort函数对已经排序的数据表现非常好。正如Anurag所指出的,在第一个情况中,sort方法处理的是已经排序的数据,而在第二个情况中,sorted方法在新的数据上工作,需要重复进行排序。
因此,我编写了这个测试脚本,并且发现它们非常接近。
""" 示例输出: $ python list_sort_timeit.py 使用sort方法:19.0166599751 使用排序内置方法:23.203567028 """
import random import timeit print '使用sort方法:', x = min(timeit.Timer("test_list1.sort()", "import random;test_list1=random.sample(xrange(1000),1000);test_list1.sort()").repeat()) print x print '使用排序内置方法:', x = min(timeit.Timer("sorted(test_list2)", "import random;test_list2=random.sample(xrange(1000),1000);test_list2.sort()").repeat()) print x
哦,我看到Alex Martelli正在回答,正如我打字时一样...(我会保留编辑,因为它可能很有用)。