本帖最后由 gocadcam 于 2011-10-11 20:21 编辑
今天又仔细看了一下代码,发现LZ与15#的方法4代码有误(本意是验证各方法的排序结果的正确性),7#的是正确的。
同时,经验证,方法5运用set进行排序,虽然速度快,但当a中有重复项时,得到的结果是错误的。
方法 3,4,6都是运用内建的List排序方法sort()对zip序列进行排序。属于同一方法。其中,以方法3的思路清晰,代码简洁,运行速度快。
以下是某次运行结果,仅供参考:
a=[9, 2, 12, 6, 4, 12, 6, 25, 6]
b=[1, 2, 3, 4, 5, 6, 7, 8, 4]
Start Method 2
[2, 4, 6, 6, 6, 9, 12, 12, 25]
[2, 5, 4, 7, 4, 1, 3, 6, 8]
Start Method 3
(2, 4, 6, 6, 6, 9, 12, 12, 25)
(2, 5, 4, 4, 7, 1, 3, 6, 8)
Start Method 4
(2, 4, 6, 6, 6, 9, 12, 12, 25)
(2, 5, 4, 4, 7, 1, 3, 6, 8)
Start Method 5
[2, 4, 6, 6, 6, 9, 12, 12, 25]
[2, 5, 4, 4, 4, 1, 6, 6, 8] #注意结果出错
Start Method 6
(2, 4, 6, 6, 6, 9, 12, 12, 25)
(2, 5, 4, 7, 4, 1, 3, 6, 8)
各方法的排序结果的速度
Start Method 3
Done
Method 3: time = 23.7781405513
Start Method 4
Done
Method 4: time = 30.7797904265
Start Method 5
Done
Method 5: time = 12.135676426 排序结果的正确性待议
Start Method 6
Done
Method 6: time = 33.2384716898
以下是测试代码:
# myTestSort.py
import random, time
## 方法 1:不能运行!对list不适用,应该转化成string 且存在重复时出错。
def mySort1( a, b ):
c = a
d = []
a.sort()
for i in a:
p = c.find(i) ## error c is not string object
d.append(b[p])
aa,bb = a,d
return aa,bb
## 方法 2:比较慢,数据量大时 不建议采用
def mySort2( a, b ):
n = len(a)-1
for i in range(n):
for j in range(n):
if a[j]>a[j+1]:
a[j],a[j+1]=a[j+1],a[j]
b[j],b[j+1]=b[j+1],b[j]
aa,bb = a,b
return aa,bb
## 方法 3:
def mySort3( a, b ):
t = zip(a,b)
t.sort()
aa,bb = zip(*t)
return aa,bb
## 方法 4:
def mySort4( a, b ):
temp_point_list = []
n = len(a)
for ii in range(n):
temp_point_list.append( ( a[ii], b[ii] ) ) ## 引用元素,而不是整个列表。temp_point_list.append( ( a[ii], b[ii] ) )
temp_point_list.sort()
aa,bb = zip(*temp_point_list) ## 应该缺少这一句
return aa,bb
## 方法 5:
def mySort5( a, b ):
cc = dict(zip(a,b))
aa = sorted(a)
bb = [cc[key] for key in aa]
return aa,bb
## 方法 6:
def mySort6( a, b ):
aa,bb = zip(*sorted(zip(a,b),key=lambda d:d[0]))
return aa,bb
## 以下是测试代码,验证各方法的排序结果的正确性
ta = [ 9, 2, 12, 6, 4, 12, 6, 25, 6 ]
tb = [ 1, 2, 3, 4, 5, 6, 7, 8, 4 ]
mySortList = [ mySort1, mySort2, mySort3, mySort4, mySort5, mySort6 ]
print ta,'\n', tb
for mi in range( 1, 6 ) :
at = ta[:]
bt = tb[:]
print 'Start Method %d' % (mi+1)
aa,bb = mySortList[mi]( at, bt )
print aa,'\n',bb # 取消行首注释,打印排序结果
## 以下是测试代码,测试各方法的排序结果的速度
num=1000000; limits=50000000 ## 可以减小数值,以便验证正确性
a=[]; b=[];
for i in range(num):
a.append(random.randint(0,limits))
b.append(random.randint(0,limits))
#print a,'\n',b # 取消行首注释,打印输入列表
#mySortList = [ mySort1, mySort2, mySort3, mySort4, mySort5, mySort6 ]
# Only test the Method 3 - 6
for mi in range( 2, 6 ) :
at = a[:]
bt = b[:]
print 'Start Method %d' % (mi+1)
time_0 = time.clock()
aa,bb = mySortList[mi]( at, bt )
time_1 = time.clock()
print 'Done'
#print aa,'\n',bb # 取消行首注释,打印排序结果
print "Method %d: time = %s"%(mi+1 ,time_1 - time_0)
方法4的代码直接粘贴,a,b列表的下标[ i ]会消失同时字体变为斜体,改成a,b [ii]就正常了
|