Python 3:何时使用dict,何时使用元组列表? [英] Python 3: When to use dict, when list of tuples?

查看:85
本文介绍了Python 3:何时使用dict,何时使用元组列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 id 个囚犯。每个囚犯都有一个名字。

I have ids 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"
}

vs

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 结构的东西的相等部分(例如,您需要按任何一个进行搜索,等等),那么最好使用元组或 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.

这篇关于Python 3:何时使用dict,何时使用元组列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆