实例一:两个列表判断s列表中的元素是否全部都在t列表中
t = [ i for i in range(1,10000000)]
s = [ i for i in range(1,5000)]
解法1:暴力解法
def test001():
sd = True
for i in s:
if i not in t:
sd = False
print(sd)
解法2:使用set自带的issubset()方法
def test002():
print(set(s).issubset(t))
性能优化对比
注:如何分析python性能,可参考我的另一篇文章python性能测试初探
实例二:去除列表K中的重复项
k = [ i for i in range(1,50000)]+[ i for i in range(1,5000)]
解法1:使用切片
def test001(a):
for i in a:
for j in a[i:]:
if i==j:
a.remove(j)
print('test1',a)
解法2:使用set()
def test002(a):
print("test2",list(set(a)))
性能优化对比
总结
set数据结构包含许多解决不同问题的方法,否则这些问题就需要通过嵌套的for/if才能实现