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

时间:2022-09-01 00:31:49

I have ids of jail *ers, for example. Each *er has a name.

例如,我有*囚犯的ids。每个囚犯都有一个名字。

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?

我知道dictionarys是如何工作的,我知道元组是如何工作的,我知道列表是如何工作的,但有时候我会看到一个字典被使用,有时候还有一个元组列表。在我的情况下我应该使用哪一个?

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,何时使用元组列表,哪一个有什么好处?

3 个解决方案

#1


6  

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 (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和name视为类似于C结构的东西的相等部分(例如,你需要通过它们中的任何一个进行搜索等),那么你最好使用元组或collections.namedtuple。您仍然可以将它们放在列表或集合中,具体取决于您是否需要保留它。

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。

#2


5  

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. 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.

    将键映射到值需要在dict中保持恒定时间,在元组列表中执行相同操作需要线性时间。因此,键值对的数量越大,扫描元组列表以查找匹配所需的时间就越多,而在字典中,查找几乎是即时的。

    (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. Even if ordering is required, you can use a collections.OrderedDict instead to get the best of both worlds.

在大多数情况下,您使用dict。即使需要订购,您也可以使用collections.OrderedDict来充分利用这两个世界。

#3


2  

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 *ers 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).
  • 字典值是可变的,这意味着可以允许它们被更改。你不能用元组做同样的事情(它是不可变的)。

E.g

例如

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.

要使用元组列表实现相同的功能,您必须使用新元组替换要操作的元组。

E.g

例如

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

#1


6  

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 (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和name视为类似于C结构的东西的相等部分(例如,你需要通过它们中的任何一个进行搜索等),那么你最好使用元组或collections.namedtuple。您仍然可以将它们放在列表或集合中,具体取决于您是否需要保留它。

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。

#2


5  

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. 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.

    将键映射到值需要在dict中保持恒定时间,在元组列表中执行相同操作需要线性时间。因此,键值对的数量越大,扫描元组列表以查找匹配所需的时间就越多,而在字典中,查找几乎是即时的。

    (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. Even if ordering is required, you can use a collections.OrderedDict instead to get the best of both worlds.

在大多数情况下,您使用dict。即使需要订购,您也可以使用collections.OrderedDict来充分利用这两个世界。

#3


2  

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 *ers 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).
  • 字典值是可变的,这意味着可以允许它们被更改。你不能用元组做同样的事情(它是不可变的)。

E.g

例如

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.

要使用元组列表实现相同的功能,您必须使用新元组替换要操作的元组。

E.g

例如

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