在 Python 中,何时使用字典、列表或集合?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3489071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Python, when to use a Dictionary, List or Set?
提问by Blankman
When should I use a dictionary, list or set?
我什么时候应该使用字典、列表或集合?
Are there scenarios that are more suited for each data type?
是否有更适合每种数据类型的场景?
采纳答案by Alex Martelli
A listkeeps order, dictand setdon't: when you care about order, therefore, you must use list(if your choice of containers is limited to these three, of course;-).
Alist保持秩序,dict而set不是:当你关心秩序时,你必须使用list(如果你选择的容器仅限于这三个,当然;-)。
dictassociates with each key a value, while listand setjust contain values: very different use cases, obviously.
dict联营公司与每个键的值,而list和set只包含值:非常不同的使用情况,效果显着。
setrequires items to be hashable, listdoesn't: if you have non-hashable items, therefore, you cannot use setand must instead use list.
set要求项目是可散列的,list而不是:如果您有不可散列的项目,因此,您不能使用,set而必须使用list.
setforbids duplicates, listdoes 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禁止重复,list不:也是一个关键的区别。(一个“多重集”,将重复项映射到不同数量的项目中,可以找到collections.Counter- 你可以将一个构建为dict,如果由于某种奇怪的原因无法导入collections,或者,在 2.7 之前Python 作为 a collections.defaultdict(int),使用项目作为键和关联的值作为计数)。
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, setis better than list.
检查 a set(或dict,对于键)中值的成员资格非常快(大约需要一个常数,很短的时间),而在列表中,它花费的时间与平均和最坏情况下的列表长度成正比。所以,如果你有可散列的项目,不管顺序还是重复,并且想要快速的成员资格检查,set都比list.
回答by Jon Skeet
- Do you just need an ordered sequence of items? Go for a list.
- Do you just need to know whether or not you've already gota particular value, but without ordering (and you don't need to store duplicates)? Use a set.
- Do you need to associate values with keys, so you can look them up efficiently (by key) later on? Use a dictionary.
- 您是否只需要有序的项目序列?去找一份清单。
- 您是否只需要知道您是否已经获得了特定值,但无需订购(并且您不需要存储重复项)?使用一套。
- 您是否需要将值与键相关联,以便以后可以有效地(按键)查找它们?使用字典。
回答by unutbu
When you want an unordered collection of unique elements, use a set. (For example, when you want the set of all the words used in a document).
如果您想要一个无序的唯一元素集合,请使用set. (例如,当您想要文档中使用的所有单词的集合时)。
When you want to collect an immutable ordered list of elements, use a tuple. (For example, when you want a (name, phone_number) pair that you wish to use as an element in a set, you would need a tuple rather than a list since sets require elements be immutable).
当您想要收集不可变的有序元素列表时,请使用tuple. (例如,当您想要一个 (name, phone_number) 对用作集合中的元素时,您需要一个元组而不是列表,因为集合要求元素是不可变的)。
When you want to collect a mutable ordered list of elements, use a list. (For example, when you want to append new phone numbers to a list: [number1, number2, ...]).
当您想要收集可变的有序元素列表时,请使用list. (例如,当您想将新电话号码附加到列表时:[number1, number2, ...])。
When you want a mapping from keys to values, use a dict. (For example, when you want a telephone book which maps names to phone numbers: {'John Smith' : '555-1212'}). Note the keys in a dict are unordered. (If you iterate through a dict (telephone book), the keys (names) may show up in any order).
当您想要从键到值的映射时,请使用dict. (例如,当您想要将姓名映射到电话号码的电话簿时:){'John Smith' : '555-1212'}。注意 dict 中的键是无序的。(如果您遍历 dict(电话簿),则键(名称)可能以任何顺序显示)。
回答by SLaks
Use a dictionary when you have a set of unique keys that map to values.
Use a list if you have an ordered collection of items.
Use a set to store an unordered set of items.
当您有一组映射到值的唯一键时,请使用字典。
如果您有有序的项目集合,请使用列表。
使用集合来存储一组无序的项目。
回答by Goose
Although this doesn't cover sets, it is a good explanation of dicts and lists:
虽然这不包括sets,但它是对dicts 和lists 的一个很好的解释:
Lists are what they seem - a list of values. Each one of them is numbered, starting from zero - the first one is numbered zero, the second 1, the third 2, etc. You can remove values from the list, and add new values to the end. Example: Your many cats' names.
Dictionaries are similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them a definition. In python, the word is called a 'key', and the definition a 'value'. The values in a dictionary aren't numbered - tare similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them a definition. The values in a dictionary aren't numbered - they aren't in any specific order, either - the key does the same thing. You can add, remove, and modify the values in dictionaries. Example: telephone book.
列表就是它们看起来的样子——一个值列表。它们中的每一个都编号,从零开始 - 第一个编号为零,第二个编号为 1,第三个编号为 2,等等。您可以从列表中删除值,并在末尾添加新值。示例:您的许多猫的名字。
字典类似于它们的名字所暗示的 - 字典。在字典中,你有一个词的“索引”,每个词都有一个定义。在python中,这个词被称为“键”,而定义被称为“值”。字典中的值没有编号 - 皮重类似于它们的名字所暗示的 - 字典。在字典中,你有一个词的“索引”,每个词都有一个定义。字典中的值没有编号——它们也没有任何特定的顺序——键做同样的事情。您可以添加、删除和修改字典中的值。例如:电话簿。
回答by Nitish Kumar Pal
Listsare what they seem - a list of values. Each one of them is numbered, starting from zero - the first one is numbered zero, the second 1, the third 2, etc. You can remove values from the list, and add new values to the end. Example: Your many cats' names.
列表就是它们看起来的样子——一个值列表。它们中的每一个都编号,从零开始 - 第一个编号为零,第二个编号为 1,第三个编号为 2,等等。您可以从列表中删除值,并在末尾添加新值。示例:您的许多猫的名字。
Tuplesare just like lists, but you can't change their values. The values that you give it first up, are the values that you are stuck with for the rest of the program. Again, each value is numbered starting from zero, for easy reference. Example: the names of the months of the year.
元组就像列表,但你不能改变它们的值。您首先给出的值是您在程序的其余部分坚持使用的值。同样,每个值都从零开始编号,以便于参考。示例:一年中月份的名称。
Dictionariesare similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them a definition. In python, the word is called a 'key', and the definition a 'value'. The values in a dictionary aren't numbered - tare similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them a definition. In python, the word is called a 'key', and the definition a 'value'. The values in a dictionary aren't numbered - they aren't in any specific order, either - the key does the same thing. You can add, remove, and modify the values in dictionaries. Example: telephone book.
字典类似于它们的名字所暗示的——字典。在字典中,你有一个词的“索引”,每个词都有一个定义。在python中,这个词被称为“键”,而定义被称为“值”。字典中的值没有编号 - 皮重类似于它们的名字所暗示的 - 字典。在字典中,你有一个词的“索引”,每个词都有一个定义。在python中,这个词被称为“键”,而定义被称为“值”。字典中的值没有编号——它们也没有任何特定的顺序——键做同样的事情。您可以添加、删除和修改字典中的值。例子:电话簿。
回答by Calculus
When use them, I make an exhaustive cheatsheet of their methods for your reference:
在使用它们时,我制作了一份详尽的备忘单供您参考:
class ContainerMethods:
def __init__(self):
self.list_methods_11 = {
'Add':{'append','extend','insert'},
'Subtract':{'pop','remove'},
'Sort':{'reverse', 'sort'},
'Search':{'count', 'index'},
'Entire':{'clear','copy'},
}
self.tuple_methods_2 = {'Search':'count','index'}
self.dict_methods_11 = {
'Views':{'keys', 'values', 'items'},
'Add':{'update'},
'Subtract':{'pop', 'popitem',},
'Extract':{'get','setdefault',},
'Entire':{ 'clear', 'copy','fromkeys'},
}
self.set_methods_17 ={
'Add':{['add', 'update'],['difference_update','symmetric_difference_update','intersection_update']},
'Subtract':{'pop', 'remove','discard'},
'Relation':{'isdisjoint', 'issubset', 'issuperset'},
'operation':{'union' 'intersection','difference', 'symmetric_difference'}
'Entire':{'clear', 'copy'}}
回答by Federico Caccia
In combination with lists, dictsand sets, there are also another interesting python objects, OrderedDicts.
结合list、dicts和set,还有另一个有趣的 Python 对象OrderedDicts。
Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.
有序字典就像普通字典一样,但它们记住插入项目的顺序。迭代有序字典时,项目将按照它们的键首次添加的顺序返回。
OrderedDictscould be useful when you need to preserve the order of the keys, for example working with documents: It's common to need the vector representation of all terms in a document. So using OrderedDictsyou can efficiently verify if a term has been read before, add terms, extract terms, and after all the manipulations you can extract the ordered vector representation of them.
当您需要保留键的顺序时,OrderedDicts可能很有用,例如处理文档:通常需要文档中所有术语的向量表示。因此,使用OrderedDicts您可以有效地验证某个术语之前是否已被读取、添加术语、提取术语,并且在所有操作之后您可以提取它们的有序向量表示。
回答by math
For C++ I was always having this flow chart in mind: In which scenario do I use a particular STL container?, so I was curious if something similar is available for Python3 as well, but I had no luck.
对于 C++,我总是牢记这个流程图:在哪种情况下我使用特定的 STL 容器?,所以我很好奇 Python3 是否也有类似的东西,但我没有运气。
What you need to keep in mind for Python is: There is no single Python standard as for C++. Hence there might be huge differences for different Python interpreters (e.g. CPython, PyPy). The following flow chart is for CPython.
对于 Python,您需要记住的是:对于 C++,没有单一的 Python 标准。因此,不同的 Python 解释器(例如 CPython、PyPy)可能存在巨大差异。以下流程图适用于 CPython。
Additionally I found no good way to incorporate the following data structures into the diagram: bytes, byte arrays, tuples, named_tuples, ChainMap, Counter, and arrays.
另外,我发现包含以下数据结构到图中,没有什么好办法:bytes,byte arrays,tuples,named_tuples,ChainMap,Counter,和arrays。
OrderedDictanddequeare available viacollectionsmodule.heapqis available from theheapqmoduleLifoQueue,Queue, andPriorityQueueare available via thequeuemodule which is designed for concurrent (threads) access. (There is also amultiprocessing.Queueavailable but I don't know the differences toqueue.Queuebut would assume that it should be used when concurrent access from processes is needed.)dict,set,frozen_set, andlistare builtin of course
OrderedDict并且deque可以通过collections模块获得。heapq可从heapq模块获得LifoQueue、Queue和PriorityQueue可通过queue专为并发(线程)访问而设计的模块获得。(还有一个multiprocessing.Queue可用的,但我不知道它们之间的区别,queue.Queue但假设在需要进程的并发访问时应该使用它。)dict,set,frozen_set, 和list当然是内置的
For anyone I would be grateful if you could improve this answer and provide a better diagram in every aspect. Feel free and welcome.

对于任何人,如果您能改进此答案并在各个方面提供更好的图表,我将不胜感激。感到自由和欢迎。

PS: the diagram has been made with yed. The graphml file is here
PS:图表是用yed制作的。graphml 文件在这里
回答by lmiguelvargasf
In short, use:
简而言之,使用:
list- if you require an ordered sequence of items.
list- 如果您需要有序的项目序列。
dict- if you require to relate values with keys
dict- 如果您需要将值与键相关联
set- if you require to keep unique elements.
set- 如果您需要保留独特的元素。
Detailed Explanation
详细说明
List
列表
A list is a mutable sequence, typically used to store collections of homogeneous items.
列表是一个可变序列,通常用于存储同类项的集合。
A list implements all of the common sequence operations:
列表实现了所有常见的序列操作:
x in landx not in ll[i],l[i:j],l[i:j:k]len(l),min(l),max(l)l.count(x)l.index(x[, i[, j]])- index of the 1st occurrence ofxinl(at or afteriand beforejindeces)
x in l和x not in ll[i],l[i:j],l[i:j:k]len(l),min(l),max(l)l.count(x)l.index(x[, i[, j]])- 第一次出现xin 的索引l(在indeces处或之后i和之前j)
A list also implements all of the mutable sequence operations:
列表还实现了所有可变序列操作:
l[i] = x- itemioflis replaced byxl[i:j] = t- slice oflfromitojis replaced by the contents of the iterabletdel l[i:j]- same asl[i:j] = []l[i:j:k] = t- the elements ofl[i:j:k]are replaced by those oftdel l[i:j:k]- removes the elements ofs[i:j:k]from the listl.append(x)- appendsxto the end of the sequencel.clear()- removes all items froml(same as dell[:])l.copy()- creates a shallow copy ofl(same asl[:])l.extend(t)orl += t- extendslwith the contents oftl *= n- updateslwith its contents repeatedntimesl.insert(i, x)- insertsxintolat the index given byil.pop([i])- retrieves the item atiand also removes it fromll.remove(x)- remove the first item fromlwherel[i]is equal to xl.reverse()- reverses the items oflin place
l[i] = x-项目i的l被替换xl[i:j] = t-lfromito 的切片j被可迭代的内容替换tdel l[i:j]- 与...一样l[i:j] = []l[i:j:k] = t- 的元素l[i:j:k]被替换为tdel l[i:j:k]-s[i:j:k]从列表中删除 的元素l.append(x)- 附加x到序列的末尾l.clear()- 删除所有项目l(与 del 相同l[:])l.copy()- 创建l(与 相同l[:])的浅拷贝l.extend(t)或l += t- 扩展l内容tl *= n-更新l其内容重复n次l.insert(i, x)-插入x到l由下式给出的指数在il.pop([i])- 检索该项目i并将其从ll.remove(x)- 从等于 x 的l地方删除第一项l[i]l.reverse()- 反转l原位的项目
A list could be used as stack by taking advantage of the methods appendand pop.
通过利用方法append和 ,可以将列表用作堆栈pop。
Dictionary
字典
A dictionary maps hashable values to arbitrary objects. A dictionary is a mutable object. The main operations on a dictionary are storing a value with some key and extracting the value given the key.
字典将可散列值映射到任意对象。字典是一个可变对象。字典上的主要操作是用某个键存储一个值并提取给定键的值。
In a dictionary, you cannot use as keys values that are not hashable, that is, values containing lists, dictionaries or other mutable types.
在字典中,不能使用不可散列的值作为键,即包含列表、字典或其他可变类型的值。
Set
放
A set is an unordered collection of distinct hashable objects. A set is commonly used to include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.
集合是不同的可散列对象的无序集合。集合通常用于包括成员资格测试、从序列中删除重复项以及计算交集、并集、差和对称差等数学运算。

