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

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


当前回答

当您需要唯一元素的无序集合时,请使用set。(例如,当您需要文档中使用的所有单词的集合时)。

当你想收集一个不可变的有序元素列表时,使用元组。(例如,当您希望将(name, phone_number)对用作集合中的元素时,您将需要元组而不是列表,因为集合要求元素是不可变的)。

当您想收集一个可变的有序元素列表时,请使用列表。(例如,当您想要将新的电话号码追加到列表:[number1, number2,…])。

当您需要从键映射到值时,请使用字典。(例如,当你想要一个将名字映射到电话号码的电话簿:{'John Smith': '555-1212'})。注意字典中的键是无序的。(如果你遍历字典(电话簿),键(名字)可能以任何顺序出现)。

其他回答

对于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文件在这里

字典:python字典就像一个哈希表,以键作为索引,对象作为值。

列表:列表用于保存数组中的对象,并根据该对象在数组中的位置进行索引。

Set: Set是一个带有函数的集合,这些函数可以判断一个对象是否存在于集合中。

当您有一组映射到值的唯一键时,请使用字典。 如果你有一个有序的项目集合,可以使用列表。 使用集合存储一组无序的项。

列表就是它们看起来的那样——一个值的列表。每一个都有编号,从0开始——第一个编号为0,第二个编号为1,第三个编号为2,以此类推。您可以从列表中删除值,并在末尾添加新值。例子:你的许多猫的名字。

元组就像列表一样,但是你不能改变它们的值。你首先给出的值,就是你在接下来的程序中一直用到的值。同样,每个值都从0开始编号,以便于参考。例如:一年中月份的名称。

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. 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.

虽然这里不包括集合,但它很好地解释了字典和列表:

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/