使用python如何为三元变量赋予0,1,2?

时间:2017-02-20 06:42:42

标签: python python-2.7 dictionary enums binary

我有csv个文件,列名为:PH,K,Zn,S,Fe ......等等。对于每列,有3种不同类型的输出,例如:

PH       S       Zn     Fe         Cu   Mn
Acidic   Low    Low     Medium  High    Medium
Alkaline High   Medium  Medium  High    High
Acidic  Medium  Low     Medium  High    High
Neutral High    Low     Medium  High    High
Acidic   Low    Low     Medium  High    High
Acidic   Low    Low     Medium  High    High
Acidic  Medium  Medium  Medium  High    High

我想提供

的值
Acidic = 0, Neutral = 1, Alkaline = 2
Low = 0, Medium = 1, High = 2

如何编写自动转换的代码Acidic = 0,Neutral = 1,Alkaline = 2?

2 个答案:

答案 0 :(得分:3)

好的,比如

<div>{{{raw_html_content}}}</div>

答案 1 :(得分:1)

Python提供Enum类。您想要使用枚举的原因涵盖here。在你的情况下,他们看起来像:

<强>代码:

from enum import Enum
PH = Enum('PH', 'Acidic Neutral Alkaline')
Concentration = Enum('Concentration', 'Low Medium High')

演示代码:

print(PH['Acidic'].value)
print(Concentration['Medium'].value)

<强>产地:

1
2

演示代码2:

for i in range(1, 4):
    ph = PH(i)
    concentration = Concentration(i)
    print(ph, ph.name, ph.value)
    print(concentration, concentration.name, concentration.value)

<强>产地:

PH.Acidic Acidic 1
Concentration.Low Low 1
PH.Neutral Neutral 2
Concentration.Medium Medium 2
PH.Alkaline Alkaline 3
Concentration.High High 3