-2

对于所有数字表示,我都有字符串“一”、“二”等文件。我希望将它们替换为实际数字 1、2、3 等。也就是说,我想要 {"zero", "one", "two", ..., "nine"} 到 {"0" , "1", ... "9"} 我怎样才能以pythonic方式做到这一点?

4

2 回答 2

1

使用关联数组,在 Python 中称为“字典”:

themap={"one":1, "two":2}   # make a dictionary
themap["one"]    # evaluates to the number 1

这适用于任何类型的数据,因此,根据您的问题,

themap={"one":"1", "two":"2"}
themap["one"]    # evaluates to the string "1"

一次映射很多值:

inputs=["one","two"]   # square brackets, so it's an array
themap={"one":1, "two":2}   # braces, so it's a dictionary
map(lambda x: themap[x], inputs)  # evaluates to [1, 2]

是一个在lambda x: themap[x]中查找项目的函数themapmap()为 的每个元素调用该函数inputs并将结果作为数组放在一起。(在 Python 2.7.3 上测试)

于 2013-10-30T16:31:54.273 回答
0

dict 将以两种方式完成这项工作:

st='zero one two three four five six seven eight nine ten'
name2num={s:i for i,s in enumerate(st.split())}
num2name={i:s for i,s in enumerate(st.split())}

print name2num
print num2name
for i, s in enumerate(st.split()):
    print num2name[i], '=>', name2num[s]

印刷:

{'seven': 7, 'ten': 10, 'nine': 9, 'six': 6, 'three': 3, 'two': 2, 'four': 4, 'zero': 0, 'five': 5, 'eight': 8, 'one': 1}
{0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten'}
zero => 0
one => 1
two => 2
three => 3
four => 4
five => 5
six => 6
seven => 7
eight => 8
nine => 9
ten => 10

您还可以使用一个类:

class Nums:
    zero=0
    one=1
    two=2
    three=3
    # etc

print Nums.zero
# 0
print Nums.one     
# 1
print getattr(Nums, 'two')
# 2

或者,使用类枚举的另一种方式:

class Nums2:
    pass

for i, s in enumerate(st.split()):
    setattr(Nums2, s, i)        

for s in st.split():
    print getattr(Nums2,s)  
# prints 0-10...

或者等待 Python 3.4 和PEP 435中描述的 Enum 类型的实现

于 2013-10-30T16:50:49.927 回答