在 Python 中,何时使用字典、列表或集合? [英] In Python, when to use a Dictionary, List or Set?

查看:109
本文介绍了在 Python 中,何时使用字典、列表或集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于在 Python 中,何时使用字典、列表或集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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