python排序和唯一vs

2024-06-02 07:44:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

b)把它们放在一套里

^{pr2}$

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


Tags: 字符串列表time排序顺序functionsomesort
1条回答
网友
1楼 · 发布于 2024-06-02 07:44:08

我做了一个简单的测试来检查两个解决方案的运行时间。第一个测试创建一个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))

我得到的输出:

^{pr2}$

相关问题 更多 >