【问题标题】:python - Sort & Unique vs Setpython - 排序和唯一与集合
【发布时间】:2016-06-29 09:52:57
【问题描述】:

在 python 2.7 中,为了从冗余字符串列表中检索唯一字符串集,首选的是什么(大约 1000 万个长度为 ~20 的字符串):

a) 对列表进行排序并删除重复的字符串

sort(l)
unique(l) #some linear time function

b) 把它们都放在一个集合中

set(l)

请注意,我不关心字符串的顺序。

【问题讨论】:

  • 您可以使用 timeit 模块来 100% 确定,但我会非常惊讶它 a) 比 b) 工作得更快,因为 a) 需要 O(n + nlogn) 而 b) 只需要 O(n)

标签: python python-2.7 sorting set unique


【解决方案1】:

我做了一个简单的测试来检查两种解决方案的运行时间。第一个测试创建一个set,第二个测试对列表进行排序(为简单起见,它不会删除重复项)。

正如预期的那样,创建一个集合比排序快得多,因为它的复杂性是O(n),而排序是O(nlogn)

import random
import string
import time


def random_str():
    size = random.randint(10, 20)
    chars = string.ascii_letters + string.digits
    return ''.join(random.choice(chars) for _ in range(size))


l = [random_str() for _ in xrange(1000000)]

t1 = time.clock()
for i in range(10):
    set(l)
t2 = time.clock()
print(round(t2-t1, 3))

t1 = time.clock()
for i in range(10):
    sorted(l)
t2 = time.clock()
print(round(t2-t1, 3))

我得到的输出:

2.77
11.83

【讨论】:

  • 使用timeit 是进行此类测量的规范方法,但无论如何这是正确的方法。衡量,不要猜测。
猜你喜欢
  • 1970-01-01
  • 2021-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-16
  • 1970-01-01
  • 2012-03-08
相关资源
最近更新 更多