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

using python how to give 0, 1 , 2 for ternary variables?

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

1
2
3
4
5
6
7
8
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

我想给出价值

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

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


好的就好了

1
2
3
4
5
6
7
8
9
10
11
dicts = {
   'PH' : {'Acidic': 0, 'Alkaline': 1, 'Neutral': 2},
   'S': {'Low': 0, 'High': 1, 'Medium': 2},
   # etc
}
with open(your_file) as file:
    table = []
    reader = csv.DictReader(file)
    for row in reader:
        new_row = {key: dicts[key][value] for (key, value) in row.items()}
        table.append(new_row)


Python提供了Enum类。 这里介绍了为什么要使用Enums。 在你的情况下,他们看起来像:

码:

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

演示代码:

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

生产:

1
2
1
2

演示代码2:

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

生产:

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