Python 3:何时使用 dict,何时使用元组列表?
问题描述
例如,我有监狱囚犯的 id
.每个囚犯都有一个名字.
I have id
s of jail prisoners, for example. Each prisoner has a name.
我知道字典是如何工作的,我知道元组是如何工作的,我知道列表是如何工作的,但有时我会看到正在使用的字典,有时是元组列表.在我的情况下我应该使用哪一个?
I know how dictionarys work and I know how tuples work and I know how lists work, but sometimes I see a dictionary being used, and sometimes a list of tuples. Which one should I use in my case?
d = {
1: "Mike",
2: "Bob",
3: "Tom"
}
对
l = [
(1, "Mike"),
(2, "Bob"),
(3, "Tom")
]
概括一下这个问题:什么时候应该使用字典,什么时候应该使用元组列表,这样做有什么好处?
And to generalize the question: WHEN should I use a dict, and when should I use a list of tuples, what are the benefits of one?
解决方案
当需要按顺序存储项目时,您应该使用列表.在这种情况下,只有将 ID 映射到名称很重要.
You should use a list when it makes sense to store items in order. In this case it only matters that ID's are mapped to names.
字典是一种映射,这意味着键和值之间的关系不是对称的.例如,通过已知值获取键是很棘手的(并且在一般情况下并不总是可能),而通过任何项的值过滤元组列表(或一组)同样容易.
A dictionary is a mapping, which means the relation between keys and values is not symmetrical. For example, it's tricky (and not always possible in the general case) to fetch a key by known value, whereas it's equally easy to filter a list (or a set, for that matter) of tuples by value of any of their items.
话虽如此,在选择数据结构时,考虑如何从中检索数据是有意义的.如果您可以将 id
和 name
视为类似于 C struct
的相同部分(例如,您需要按其中任何一个进行搜索,等)那么你最好使用元组或 collections.namedtuple
.您仍然可以将它们放在一个列表或一组中,具体取决于您保持有序的需要.
That being said, when choosing the data structure, it makes sense to consider how you are going to retrieve data from it. If you can see id
and name
as equal parts of something resembling a C struct
(e.g. you'll need to search by any of them, etc.) then you're better off using a tuple or a collections.namedtuple
. You can still put them in a list or a set depending on your need to keep it ordered.
但如果 id
是一个特殊"字段,用于检索有关对象的其余信息,并且它保证是唯一的(嗯,ID"是指它),并且您不需要内部顺序,并且您想要恒定时间随机访问 - 当然使用字典.
But if id
is a "special" field that is used to retrieve the rest of the info about the object, and it's guaranteed to be unique (well, "ID" means it), and you don't need internal order, and you want constant time random access -- of course use a dict.
相关文章