在Python中翻译用户输入

1 投票
2 回答
1036 浏览
提问于 2025-04-17 07:12

我想把一个列表里的数字(比如 [1,2,3,4,5,6,7,8,9])转换成另一个列表里的名字(比如这些数字的英文名称)。

而且,我希望能做到这样的转换:当用户输入'1'时,能显示"one"(一),输入'2'时,显示"two"(二),以此类推。

这是我目前写的代码:

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
names = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 
         'eight', 'nine']
myDict = dict(zip(numbers, names))

2 个回答

0

它不会打印“nom piods”,因为你没有“nom poids”的键。

这样做就能达到你想要的效果:

mydict = {'nom':'x', 'poids':'y','foo':'bar'}
print mydict['nom'],mydict['poids']

如果你总是使用数字,而不是文字 - 你可以这样做:

words = ['zero','one','two','three','four','five']
print words[0] # This will print 'zero'
print words[1] # This will print 'one'

print words['1'] # This will not work, you need to use 1 and not '1'
2

使用 input 这个函数可以让你从用户那里获取输入,然后进行查找(如果我理解你的意思的话):

>>> mydict = {'nom':'singe', 'poids':70, 'taille':1.75}
>>> myvar = input()
nom
>>> print(mydict[myvar])
singe

撰写回答