什么时候应该使用字典、列表或集合?
是否存在更适合每种数据类型的场景?
什么时候应该使用字典、列表或集合?
是否存在更适合每种数据类型的场景?
当前回答
虽然这里不包括集合,但它很好地解释了字典和列表:
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/
其他回答
当您有一组映射到值的唯一键时,请使用字典。 如果你有一个有序的项目集合,可以使用列表。 使用集合存储一组无序的项。
就OP问的问题而言,可能跑题了-
List:有序、可变对象的不可分解集合。 元组:有序的、不可变对象的可哈希集合,如 列表。 Set:一个不可哈希的无序、可变和不同的集合 对象。 Frozenset:无序、不可变和的可哈希集合 不同的对象。 字典:可变对象的不可哈希的无序集合 将哈希值映射到任意值。
要从视觉上比较它们,一目了然,请看图-
当您需要唯一元素的无序集合时,请使用set。(例如,当您需要文档中使用的所有单词的集合时)。
当你想收集一个不可变的有序元素列表时,使用元组。(例如,当您希望将(name, phone_number)对用作集合中的元素时,您将需要元组而不是列表,因为集合要求元素是不可变的)。
当您想收集一个可变的有序元素列表时,请使用列表。(例如,当您想要将新的电话号码追加到列表:[number1, number2,…])。
当您需要从键映射到值时,请使用字典。(例如,当你想要一个将名字映射到电话号码的电话簿:{'John Smith': '555-1212'})。注意字典中的键是无序的。(如果你遍历字典(电话簿),键(名字)可能以任何顺序出现)。
虽然这里不包括集合,但它很好地解释了字典和列表:
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/
你只是需要一个有序的项目序列吗?列个清单。 您是否只需要知道您是否已经获得了一个特定的值,但不需要进行排序(并且您不需要存储副本)?使用一个集合。 您是否需要将值与键相关联,以便稍后可以有效地(按键)查找它们?使用字典。