[英]Two-way mapping between strings and integers
Given a collection of pairs of strings and (non-contiguous) integers, which are known in advance, a Python dictionary literal is a straightforward way to define a mapping from either to the other. 给定一组字符串和(非连续的)整数(事先已知),Python字典文字是一种直接定义从一个映射到另一个映射的方法。
But supposing some parts of your program will have a string and want the corresponding integer, and others will have an integer and want the corresponding string, what's the best way to arrange this? 但是假设你的程序的某些部分将有一个字符串并且想要相应的整数,而其他部分将有一个整数并且想要相应的字符串,那么最好的方法是什么呢? Of course I could write out two separate dictionary literals, but that violates DRY, or I could do a bit of hacking with a function that uses globals() to create two dictionary variables from a single set of inputs, but I'm not sure how idiomatic that is. 当然我可以写出两个单独的字典文字,但是这违反了DRY,或者我可以用一个使用globals()从一组输入创建两个字典变量的函数做一些黑客攻击,但我不确定这是多么惯用。 What's the recommended way? 推荐的方式是什么? (I'm using Python 2.7 if it matters.) (如果重要,我正在使用Python 2.7。)
您可以从第一个映射自动生成第二个映射:
d2 = {v:k for k, v in d1.items()}
您可以使用bidict https://pypi.python.org/pypi/bidict执行此操作。
Instead of using a pair of dict
s, why not use an enum
? 而不是使用一对dict
,为什么不使用enum
?
Of course the stdlib enum
module requires 3.4, but its source is available to read and backport, or you can get the semi-official backport off PyPI, or any of the dozens of other enum
packages . 当然,STDLIB enum
模块需要3.4,但它的来源可以阅读和反向移植,或者你可以得到半官方的反向移植过的PyPI,或任何其他几十个的enum
包 。
For example: 例如:
>>> import enum
>>> class Color(enum.Enum):
... red = 1
... green = 2
... blue = 3
>>> Color.red
<Color.red: 1>
>>> Color['red']
<Color.red: 1>
>>> Color(1)
<Color.red: 1>
>>> Color(1).name
'red'
>>> Color['red'].value
1
My guess is, most of the time you won't actually be mapping back and forth between these, but just using Color.red
, instead of your current "red"
or 1
, as a value. 我的猜测是,大多数时候你实际上不会在这些之间来回映射,而只是使用Color.red
而不是当前的"red"
或1
作为值。 (If you want to be able to use the value directly as either an int
or a str
, look at the other classes in the docs.) (如果您希望能够将该值直接用作int
或str
,请查看文档中的其他类。)
There should be good examples all over the 3.4 stdlib of how to convert code that used to use numbers and map them to strings and vice-versa into code that uses Enum
s instead. 在3.4 stdlib中应该有很好的例子,如何转换用于使用数字的代码并将它们映射到字符串,反之亦然,代之以使用Enum
的代码。 Unfortunately, as of 3.4b1, most of those examples haven't been written yet… I believe socket.AddressFamily
and a few related types are the only ones that have made it so far. 不幸的是,从3.4b1开始,大多数这些例子还没有编写......我相信socket.AddressFamily
和一些相关的类型是迄今为止唯一的类型。 But if you can't figure it out, show an MCVE , and it should be easy to show you how to convert it. 但如果你无法弄明白,请展示一个MCVE ,它应该很容易向你展示如何转换它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.