在 Python 中,字典用于鍵/值對。然而,嵌套串列或陣列可以對大串列中的二值串列做同樣的事情。
陣列有更多用途,但字典更直接。使用字典與陣列的優缺點是什么?
uj5u.com熱心網友回復:
If you use a list of key/value pairs, getting the value corresponding to a key requires a linear search, which is 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.
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. You can write 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.
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.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/497568.html
上一篇:從Python字典中訪問多個資料
