在Python中,何时使用Dictionary,List或Set? [英] In Python, when to use a Dictionary, List or Set?
问题描述
是否有更适合每种数据类型的场景?
A 列表
保持订单, dict
code> set do not:当您关心订单时,因此您必须使用列表
(如果您选择的容器有限制对于这三个,当然; - )。
dict
与每个键值相关联,而列表
和设置
只包含值:显然非常不同的用例。
设置
要求项可以散列,列表
不:如果您有不可哈希的项目,您不能使用设置
,而必须使用列表
。
设置
禁止重复,列表
不:也是一个关键的区别。 (多重集,将重复项映射到不止一次存在的项目的不同数量,可以在 collections.Counter
中找到 - 您可以构建一个 dict
,如果由于某些奇怪的原因,您无法导入集合
,或者在2.7之前的Python作为 collections.defaultdict(int)
,使用项目作为密钥,相关联的值作为计数)。
集合中的值
(或 dict
,对于键)是快速的(取决于一个恒定的,短的时间)在列表中,平均和最差情况下,列表长度需要时间成正比。所以,如果你有哈希的项目,不要关心任何方式关于订单或重复,并希望快速成员资格检查,设置
比列表
。
When should I use a dictionary, list or set?
Are there scenarios that are more suited for each data type?
A list
keeps order, dict
and set
don't: when you care about order, therefore, you must use list
(if your choice of containers is limited to these three, of course;-).
dict
associates with each key a value, while list
and set
just contain values: very different use cases, obviously.
set
requires items to be hashable, list
doesn't: if you have non-hashable items, therefore, you cannot use set
and must instead use list
.
set
forbids duplicates, list
does not: also a crucial distinction. (A "multiset", which maps duplicates into a different count for items present more than once, can be found in collections.Counter
-- you could build one as a dict
, if for some weird reason you couldn't import collections
, or, in pre-2.7 Python as a collections.defaultdict(int)
, using the items as keys and the associated value as the count).
Checking for membership of a value in a set
(or dict
, for keys) is blazingly fast (taking about a constant, short time), while in a list it takes time proportional to the list's length in the average and worst cases. So, if you have hashable items, don't care either way about order or duplicates, and want speedy membership checking, set
is better than list
.
这篇关于在Python中,何时使用Dictionary,List或Set?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!