在Python中,何时使用Dictionary,List或Set? [英] In Python, when to use a Dictionary, List or Set?

查看:165
本文介绍了在Python中,何时使用Dictionary,List或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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆