在 Python 中,何时使用 Dictionary、List 或 Set?

2022-01-17 00:00:00 python list dictionary data-structures set

问题描述

什么时候应该使用字典、列表或集合?

When should I use a dictionary, list or set?

是否有更适合每种数据类型的场景?

Are there scenarios that are more suited for each data type?


解决方案

list 保持顺序,dictset 不:因此,当您关心订单时,您必须使用 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 将每个键与一个值相关联,而 listset 只包含值:显然,用例非常不同.

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,用于键)中的值的成员资格非常快(大约需要一个常数,很短的时间),而在一个列表中在平均和最坏情况下,它所花费的时间与列表的长度成正比.所以,如果你有可散列的项目,不关心顺序或重复,并且想要快速的成员资格检查,setlist 更好.

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.

相关文章