In Python, when to use a Dictionary, List or Set?(在 Python 中,何时使用 Dictionary、List 或 Set?)
问题描述
什么时候应该使用字典、列表或集合?
When should I use a dictionary, list or set?
是否有更适合每种数据类型的场景?
Are there scenarios that are more suited for each data type?
推荐答案
list 保持顺序,dict 和 set 不:因此,当您关心订单时,您必须使用 list(当然,如果您选择的容器仅限于这三个 ;-)).
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 将每个键与一个值相关联,而 list 和 set 只包含值:显然,用例非常不同.
dict associates each key with a value, while list and set just contain values: very different use cases, obviously.
set 要求项目是可散列的,list 不要求:如果您有不可散列的项目,则不能使用 set并且必须改为使用 list.
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 禁止重复,list 不:也是一个关键的区别.(可以在 collections.Counter 中找到multiset",它将重复项映射到多次出现的项目的不同计数 - 您可以将其构建为 dict,如果由于某些奇怪的原因您无法导入 collections,或者在 2.7 之前的 Python 中作为 collections.defaultdict(int),使用项目作为键和关联的值作为计数).
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).
检查 set(或 dict,用于键)中的值的成员资格非常快(大约需要一个常数,很短的时间),而在一个列表中在平均和最坏情况下,它所花费的时间与列表的长度成正比.所以,如果你有可散列的项目,不关心顺序或重复,并且想要快速的成员资格检查,set 比 list 更好.
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Python 中,何时使用 Dictionary、List 或 Set?
基础教程推荐
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
