Python 比较集合和列表的性能

列表中的元素可以使用下标运算符来访问。但是,集合并不支持下标运算符,因为集合中的元素是无序的。使用for循环遍历集合中的所有元素。现在,我们进行一个有趣的实验来测试集合和列表的性能。
1)检测一个元素是否在集合和列表中的各自的执行时间。
2)检测从集合和列表中删除元素时各自的执行时间。
import random
import time

NUMBER_OF_ELEMENTS = 10000

# Create a list
lst = list(range(NUMBER_OF_ELEMENTS))
random.shuffle(lst)

# Create a set from the list
s = set(lst)

# Test if an element is in the set
startTime = time.time()
for i in range(NUMBER_OF_ELEMENTS):
    i in s
endTime = time.time()
runTime = int((endTime - startTime) * 1000)
print "To test if ", NUMBER_OF_ELEMENTS, \
       "elements are in the set\n", \
       "the runtime is ", runTime, "milliseconds"

# Test if an element is in the list
startTime = time.time()
for i in range(NUMBER_OF_ELEMENTS):
    i in lst
endTime = time.time()
runTime = int((endTime - startTime) * 1000)
print "\n To test if", NUMBER_OF_ELEMENTS, \
       "elements from the set \n" , \
       "the runtime is ", runTime, "millseconds"

# Remove elements from a set one at a time
startTime = time.time()
for i in range(NUMBER_OF_ELEMENTS):
    s.remove(i)
endTime = time.time()
runTime = int((endTime - startTime) * 1000)
print "\n To remove", NUMBER_OF_ELEMENTS, \
    "elements from the set\n", \
    "the runtime is ", runTime, "milliseconds"

#  Remove elements from a list one at a time
startTime = time.time()
for i in range(NUMBER_OF_ELEMENTS):
    lst.remove(i)
endTime = time.time()
runTime = int((endTime - startTime) * 1000)
print "\n To remove", NUMBER_OF_ELEMENTS,\
    "elements from the list \n", \
    "the runtime is ", runTime, "milliseconds"

—摘自《Python 语言程序设计》 李娜译

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值