什么时候应该使用字典、列表或集合?
是否存在更适合每种数据类型的场景?
什么时候应该使用字典、列表或集合?
是否存在更适合每种数据类型的场景?
当前回答
列表就是它们看起来的那样——一个值的列表。每一个都有编号,从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.
其他回答
就OP问的问题而言,可能跑题了-
List:有序、可变对象的不可分解集合。 元组:有序的、不可变对象的可哈希集合,如 列表。 Set:一个不可哈希的无序、可变和不同的集合 对象。 Frozenset:无序、不可变和的可哈希集合 不同的对象。 字典:可变对象的不可哈希的无序集合 将哈希值映射到任意值。
要从视觉上比较它们,一目了然,请看图-
当您有一组映射到值的唯一键时,请使用字典。 如果你有一个有序的项目集合,可以使用列表。 使用集合存储一组无序的项。
与列表、字典和集合相结合,还有另一个有趣的python对象OrderedDicts。
有序字典就像普通字典一样,但是它们会记住条目插入的顺序。在有序字典上迭代时,项将按照键第一次添加的顺序返回。
OrderedDicts在需要保留键的顺序时可能很有用,例如处理文档:通常需要文档中所有术语的向量表示。因此,使用OrderedDicts,您可以有效地验证一个项之前是否已读取,添加项,提取项,在所有操作之后,您可以提取它们的有序向量表示。
虽然这里不包括集合,但它很好地解释了字典和列表:
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是一个带有函数的集合,这些函数可以判断一个对象是否存在于集合中。