简体   繁体   English

Python 3:什么时候使用dict,当元组列表?

[英]Python 3: When to use dict, when list of tuples?

I have id s of jail prisoners, for example. 我有id监狱囚犯的S,例如。 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. 我知道dictionarys是如何工作的,我知道元组是如何工作的,我知道列表是如何工作的,但有时候我会看到一个字典被使用,有时候会看到一个元组列表。 Which one should I use in my case? 在我的情况下我应该使用哪一个?

d = {
    1: "Mike",
    2: "Bob",
    3: "Tom"
}

vs 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? 并概括了这个问题:我应该何时使用dict,何时使用元组列表,哪一个有什么好处?

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. 在这种情况下,唯一重要的是ID被映射到名称。

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. 例如,通过已知值获取密钥是棘手的(并且在一般情况下并不总是可行),而通过任何项的值过滤元组的列表(或者一组)也是同样容易的。

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 (eg you'll need to search by any of them, etc.) then you're better off using a tuple or a collections.namedtuple . 如果你可以看到idname是类似于C struct的东西的相等部分(例如,你需要通过它们中的任何一个进行搜索等),那么你最好使用元组或collections.namedtuple You can still put them in a list or a set depending on your need to keep it ordered. 您仍然可以将它们放在列表或集合中,具体取决于您是否需要保留它。

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. 但是如果id是一个“特殊”字段,用于检索有关该对象的其余信息,并且它保证是唯一的(好吧,“ID”表示它),并且您不需要内部订单,而您想要恒定时间随机访问 - 当然使用dict。

There are two major differences between them: 它们之间有两个主要区别:

  • Dictionaries are unordered, a list of tuples is. 字典是无序的,元组列表是。 So if ordering matters, use the latter. 因此,如果订购很重要,请使用后者。

  • Mapping a key to a value takes constant time in a dict, doing the same in a list of tuples takes linear time. 将键映射到值在dict中占用恒定时间,在元组列表中执行相同操作需要线性时间。 So, the larger your amount of key-value pairs, the more time it'll take to scan the list of tuples to find a match, while in a dictionary the lookup is near-instant, always. 因此,键值对的数量越大,扫描元组列表以查找匹配所需的时间就越多,而在字典中,查找几乎是即时的。

    (If your tuples are kept in sorted order, you can reduce search time to O(log n) by using binary search; but that's still slower than constant time for dictionaries). (如果您的元组按排序顺序保存,则可以使用二进制搜索将搜索时间缩短为O(log n);但这仍然比字典的常量时间慢。

In most cases, you use a dict . 在大多数情况下,您使用dict Even if ordering is required, you can use a collections.OrderedDict instead to get the best of both worlds. 即使需要订购,您也可以使用collections.OrderedDict来获得两全其美。

In your case, I would use a dictionary. 在你的情况下,我会使用字典。 There are several reasons you might want to consider using one. 您可能需要考虑使用一个原因。

  • The dictionary allows for usage of its API to manipulate keys and values inside it, something that would require more code to with a list of tuples. 字典允许使用其API来操作其中的键和值,这需要更多代码来使用元组列表。

For instance, consider this: 例如,考虑一下:

To get the names of the prisoners using the dictionary, you just do this: 要使用字典获取囚犯的姓名,您只需执行以下操作:

d.values()

To do the same thing with the list of tuples you would need to do this: 要使用元组列表执行相同的操作,您需要执行此操作:

names = []
for tup in l:
    names.append(tup[1])
  • The dictionary values are mutable , meaning they can be allowed to be changed. 字典值是可变的 ,这意味着可以允许它们被更改。 You can not do the same thing with a tuple (it is immutable ). 你不能用元组做同样的事情 (它是不可变的 )。

Eg 例如

d[1] = 'Fotis'

To achieve the same thing with a list of tuples, you would have to substitute the tuple that you want to manipulate with a new one. 要使用元组列表实现相同的功能,您必须使用新元组替换要操作的元组。

Eg 例如

l[1] = (2, 'Max')

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

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