在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实现,用例要求执行迭代。列表是一种低级实现,需要大量内存开销。
推荐文章
- 在SQL Server上使用varchar(MAX) vs TEXT
- .toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])?
- 如何在Flask-SQLAlchemy中按id删除记录
- 在Python中插入列表的第一个位置
- 在javascript中从平面数组构建树数组
- Python Pandas只合并某些列
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?
- 使用Python请求的异步请求
- 是什么导致JNI调用变慢?