简体   繁体   English

Python中的枚举和2D数组?

[英]Enumeration and 2D arrays in Python?

I'm currently working on some code in Python, and I have the following enumerations: 我目前正在使用Python处理某些代码,并且具有以下枚举:

#Enumeration - matter type
matterType = ['matter', 'antimatter']
enumMatterType = enumerate(matterType)

#Enumeration  - flavor
flavor = ['electron', 'mu', 'tau']
enumFlavor = enumerate(flavor)

I've also created a 2D array: 我还创建了一个2D数组:

alpha = [[alpha_electron, alpha_anti_electron], 
        [alpha_mu, alpha_anti_mu], 
        [alpha_tau, alpha_anti_tau]]

Which is supposed to be an array of constants that I have defined earlier. 这应该是我之前定义的常量数组。 I'm using these constants in an equation, but I'm referencing them as alpha[0][0] or alpha[0][1] , etc. I feel like when someone looks at my code, they would understand it better if I had something like alpha[matter][electron] or alpha[antimatter][electron] . 我在方程式中使用这些常量,但将它们称为alpha[0][0]alpha[0][1]等。我觉得当有人看着我的代码时,他们会更好地理解它如果我有类似alpha[matter][electron]alpha[antimatter][electron] Is there any way to use the enumeration from earlier to define my variables from the array like this? 有什么办法可以使用像以前那样的枚举从数组中定义我的变量? How can I use enumeration with arrays in general? 一般如何在数组中使用枚举? How would I be able to write my alpha values with the enumeration? 如何使用枚举写入我的Alpha值? Please let me know if any part of this does not make sense - I would be happy to clarify. 请让我知道其中的任何部分是否有意义-我很乐意澄清。

You should consider a dictionary with tuple keys: 您应该考虑带有元组键的字典:

matterType = ['matter', 'antimatter']
flavor = ['electron', 'mu', 'tau']

alpha = [['alpha_electron', 'alpha_anti_electron'], 
        ['alpha_mu', 'alpha_anti_mu'], 
        ['alpha_tau', 'alpha_anti_tau']]

ref_dict = {}
for x, pair_item in enumerate(flavor):
    for y, item in enumerate(matterType):
        ref_dict[(item, pair_item)] = alpha[x][y]

Now let's say I want "matter" and "mu": 现在假设我要“ matter”和“ mu”:

In[60]: ref_dict[('matter', 'mu')]
Out[60]: 'alpha_mu'

If you want to create a set of enumeration constants, that's exactly what the enum module is for. 如果要创建一组枚举常量,那么这正是enum模块的用途。

In your case, you want enumeration constants that have an integer value, so you can use them as indexes into a list. 在您的情况下,您需要具有整数值的枚举常量,因此可以将它们用作列表的索引。 For that, you want IntEnum : 为此,您需要IntEnum

from enum import IntEnum

class MatterType(IntEnum):
    MATTER = 0
    ANTIMATTER = 1

class Flavor(IntEnum):
    ELECTRON = 0
    MU = 1
    TAU = 2

And now, instead of this: 现在,代替这个:

alpha[0][0]

… you can write this: ……你可以这样写:

alpha[MatterType.MATTER][Flavor.ELECTRON]

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

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