在Python中,哪种数据结构更高效/快速?假设顺序对我来说不重要,无论如何我都会检查重复,Python集比Python列表慢吗?


当前回答

列表性能:

>>> import timeit
>>> timeit.timeit(stmt='10**6 in a', setup='a = list(range(10**6))', number=1000)
15.08

设置性能:

>>> timeit.timeit(stmt='10**6 in a', setup='a = set(range(10**6))', number=1000)
3.90e-05

您可能想考虑元组,因为它们类似于列表,但不能修改。它们占用的内存更少,访问速度更快。它们没有列表那么灵活,但比列表更有效。它们的正常用途是作为字典键。

集合也是序列结构,但与列表和元组有两个不同。尽管集合确实有一个顺序,但这个顺序是任意的,不受程序员的控制。第二个区别是集合中的元素必须是唯一的。

根据定义设置。[python | wiki]。

>>> x = set([1, 1, 2, 2, 3, 3])
>>> x
{1, 2, 3}

其他回答

设置因近即时“包含”检查而获胜:https://en.wikipedia.org/wiki/Hash_table

列表实现:通常是一个数组,低层接近金属,适合迭代和随机访问的元素索引。

Set implementation: https://en.wikipedia.org/wiki/Hash_table, it does not iterate on a list, but finds the element by computing a hash from the key, so it depends on the nature of the key elements and the hash function. Similar to what is used for dict. I suspect list could be faster if you have very few elements (< 5), the larger element count the better the set will perform for a contains check. It is also fast for element addition and removal. Also always keep in mind that building a set has a cost !

注意:如果列表已经排序,那么在小列表上搜索列表可能会非常快,但是对于更多的数据集,对于包含检查会更快。

列表性能:

>>> import timeit
>>> timeit.timeit(stmt='10**6 in a', setup='a = list(range(10**6))', number=1000)
15.08

设置性能:

>>> timeit.timeit(stmt='10**6 in a', setup='a = set(range(10**6))', number=1000)
3.90e-05

您可能想考虑元组,因为它们类似于列表,但不能修改。它们占用的内存更少,访问速度更快。它们没有列表那么灵活,但比列表更有效。它们的正常用途是作为字典键。

集合也是序列结构,但与列表和元组有两个不同。尽管集合确实有一个顺序,但这个顺序是任意的,不受程序员的控制。第二个区别是集合中的元素必须是唯一的。

根据定义设置。[python | wiki]。

>>> x = set([1, 1, 2, 2, 3, 3])
>>> x
{1, 2, 3}

集合更快,而且你可以得到更多有集合的函数,比如你有两个集合:

set1 = {"Harry Potter", "James Bond", "Iron Man"}
set2 = {"Captain America", "Black Widow", "Hulk", "Harry Potter", "James Bond"}

我们可以很容易地连接两个集合:

set3 = set1.union(set2)

找出两者的共同点:

set3 = set1.intersection(set2)

找出两者的不同之处:

set3 = set1.difference(set2)

还有更多!试试吧,很有趣的!此外,如果你必须处理两个列表中的不同值或两个列表中的通用值,我更喜欢将列表转换为集合,许多程序员都是这样做的。 希望它能帮助你:-)

from datetime import datetime
listA = range(10000000)
setA = set(listA)
tupA = tuple(listA)
#Source Code

def calc(data, type):
start = datetime.now()
if data in type:
print ""
end = datetime.now()
print end-start

calc(9999, listA)
calc(9999, tupA)
calc(9999, setA)

比较所有3个迭代10次后的输出: 比较

我建议使用Set实现,用例仅限于引用或搜索存在,而使用Tuple实现,用例要求执行迭代。列表是一种低级实现,需要大量内存开销。