元组也没比列表快多少呀,当作遍历操作的时候。

2011-04-02  李琪 

#-*- coding:utf-8 -*-
'''
Created on 2011-4-2
作者: 李昱彤
Email: liqi1031@gmail.com
'''
aList=[]
loop=1
try:
    while loop <= 20000001:
        aList.append(loop)
        loop = loop + 1
except MemoryError:
    print "Memory is out of scope."
    import sys
    sys.exit()
aTuple=tuple(aList)
evenNumber1 = 0
oddNumber1 = 0
import time
startTime1=time.time()
for i in aTuple:
    #i is an even number
    if not i % 2:
        evenNumber1 = evenNumber1 + 1
   
    #i is an odd number
    if i % 2:
        oddNumber1 = oddNumber1 + 1
print "Total number are %s" % len(aTuple)
print "even number are %s" % evenNumber1
print "odd number are %s" % oddNumber1   
print "Costed time are %s seconds" % round((time.time() - startTime1),3)
evenNumber2 = 0
oddNumber2 = 0
startTime2=time.time()
for x in aList:
    #x is an even number
    if not x % 2:
        evenNumber2 = evenNumber2 + 1
    #x is an odd number
    if x % 2:
        oddNumber2 = oddNumber2 + 1
print "\nTotal number are %s" % len(aList)
print "even number are %s" % evenNumber2
print "odd number are %s" % oddNumber2
print "Costed time are %s seconds" % round((time.time() - startTime2),3)
 
 
测试结果:
元组:
Total number are 20000001
even number are 10000000
odd number are 10000001
Costed time are 8.437 seconds
列表:
Total number are 20000001
even number are 10000000
odd number are 10000001
Costed time are 9.064 seconds
315°/3154 人阅读/0 条评论 发表评论

登录 后发表评论