简体   繁体   English

使用字典与嵌套列表/数组的优缺点是什么?

[英]What are the pros and cons of using a dictionary versus a nested list/array?

In Python, dictionaries are used for key/value pairs.在 Python 中,字典用于键/值对。 Nested lists, or arrays, however, can do the same thing with two-value lists inside a big list.然而,嵌套列表或数组可以对大列表中的二值列表做同样的事情。

Arrays have more uses, but dictionaries are more straightforward.数组有更多用途,但字典更直接。 What are the pros and cons of using a dictionary versus an array?使用字典与数组的优缺点是什么?

If you use a list of key/value pairs, getting the value corresponding to a key requires a linear search, which is O(n).如果使用键/值对的列表,获取键对应的值需要进行线性搜索,即 O(n)。 If the list is sorted by the keys you can improve that to O(log n), but then adding to the list becomes more complicated and expensive since you have to keep it sorted.如果列表按键排序,您可以将其改进为 O(log n),但是添加到列表会变得更加复杂和昂贵,因为您必须保持排序。

Dictionaries are implemented as hash tables, so getting the value corresponding to a key is amortized constant time.字典被实现为哈希表,因此获取与键对应的值是摊销常数时间。

Furthermore, Python provides convenient syntax for looking up keys in a dictionary.此外,Python 提供了方便的语法来查找字典中的键。 You can write dictname[key] .你可以写dictname[key] Since lists aren't intended to be used as lookup tables, there's no corresponding syntax for finding a value by key there.由于列表不打算用作查找表,因此没有相应的语法来通过键查找值。 listname[index] gets an element by its numeric position, not looking up the key in a key/value pair. listname[index]通过其数字位置获取元素,而不是在键/值对中查找键。

Of course, if you want to use an association list, there's nothing stopping you from writing your own functions to do so.当然,如果您想使用关联列表,没有什么能阻止您编写自己的函数来这样做。 You could also embed them in a class and define appropriate methods so you can use [] syntax to get and set them.您还可以将它们嵌入到一个类中并定义适当的方法,以便您可以使用[]语法来获取和设置它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM