什么时候应该使用字典、列表或集合?
是否存在更适合每种数据类型的场景?
什么时候应该使用字典、列表或集合?
是否存在更适合每种数据类型的场景?
当前回答
在使用它们的时候,我为它们的方法做了一个详尽的备忘单,供你参考:
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'}}
其他回答
虽然这里不包括集合,但它很好地解释了字典和列表:
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.
http://www.sthurlow.com/python/lesson06/
你只是需要一个有序的项目序列吗?列个清单。 您是否只需要知道您是否已经获得了一个特定的值,但不需要进行排序(并且您不需要存储副本)?使用一个集合。 您是否需要将值与键相关联,以便稍后可以有效地(按键)查找它们?使用字典。
字典:python字典就像一个哈希表,以键作为索引,对象作为值。
列表:列表用于保存数组中的对象,并根据该对象在数组中的位置进行索引。
Set: Set是一个带有函数的集合,这些函数可以判断一个对象是否存在于集合中。
与列表、字典和集合相结合,还有另一个有趣的python对象OrderedDicts。
有序字典就像普通字典一样,但是它们会记住条目插入的顺序。在有序字典上迭代时,项将按照键第一次添加的顺序返回。
OrderedDicts在需要保留键的顺序时可能很有用,例如处理文档:通常需要文档中所有术语的向量表示。因此,使用OrderedDicts,您可以有效地验证一个项之前是否已读取,添加项,提取项,在所有操作之后,您可以提取它们的有序向量表示。
对于c++,我总是在脑海中有这样的流程图:在哪个场景中使用特定的STL容器?,所以我很好奇Python3中是否也有类似的东西,但我运气不好。
对于Python,你需要记住的是:Python没有像c++那样单一的标准。因此,不同的Python解释器(例如CPython, PyPy)可能存在巨大的差异。下面是CPython的流程图。
此外,我发现没有好办法将以下数据结构合并到图表中:字节、字节数组、元组、named_tuples、ChainMap、计数器和数组。
OrderedDict和deque可以通过collections模块获得。 Heapq可以从Heapq模块获得 LifoQueue、Queue和PriorityQueue可以通过Queue模块使用,Queue模块是为并发(线程)访问而设计的。(还有一个多处理。队列可用,但我不知道与队列的区别。队列,但假定它应该在需要从进程进行并发访问时使用。) Dict, set, frozen_set和list当然是内置的
对于任何人,如果你能改进这个答案,并在每个方面提供一个更好的图表,我将非常感激。请随意,欢迎光临。
PS:图是用yed做的。graphml文件在这里