我在Python中遇到字典问题。我是一个新学习者。我有一个正在处理的作业问题,正在努力解决作业问题。有人可以给我一些有关编码此问题的方法的想法吗?
#我想知道一些有关如何开始这个家庭作业问题的想法。我已经尝试了很多东西,但仍然遇到麻烦。
trans = {'0':'ling', '1':'yi', '2':'er','3':'san', '4':'si','5':'wu', '6':'liu' ,'7':'qi', '8':'ba', '9':'jiu', '10':'shi'}
def convert_to_mandarin(us_num):
## us_num , a string representing a US number 0 to 99
convert_to_mandarin('26')
将返回er shi liu
; '30'
,san shi
。
有人可以帮我解决这个问题吗?
我在将数字打印到10以上时遇到麻烦。我应该编写一段代码,该代码将返回英文数字的中文“数字”(例如,应返回“ 36”的“ san shi liu” “。)如果是14,则应返回” shi si“。
trans = { '0':'ling', '1':'yi', '2':'er', '3':'san', '4':'si', '5':'wu', '6':'liu', '7':'qi', '8':'ba', '9':'jiu', '10':'shi'}
def convert_to_mandarian(us_num):
ten = 'shi'
chinese_trans = ''
for n in str(us_num):
if n in trans.keys():
chinese_trans += trans[n]
else:
if n > 10:
chinese_trans +=str(ten) + trans[str(us_num[-1:])]
chinese_trans += trans[str(us_num[:1])] + str(ten) + trans[str(us_num[-1:])]
if n == 10 or n == 20 or n == 30 or n == 40...........90:
chinese_trans += trans[str(us_num[:1])] + str(ten)
return chinese_trans
print(convert_to_mandarian('14'))will return shi si
--------------------------('36')will return san shi liu
--------------------------('20')will return er shi```
When I run my code, I only get less than 10. So, for example, for 36 I get "san-liu" instead of "san shi liu". What am I doing wrong? I'm a new learner of Python, so I'm sorry if this question isn't very specific.
答案 0 :(得分:0)
尝试一下
trans = { '0':'ling', '1':'yi', '2':'er', '3':'san', '4':'si', '5':'wu', '6':'liu', '7':'qi', '8':'ba', '9':'jiu'}
def conv(number): #function which should accepts numbers
try:
num_str = str(number) #Converts to string
if len(num_str) == 1:
num_str = '0' + num_str #Adds e10 numeral position
else:
num_str = num_str[-2:] #Keeps last two digits
if num_str[0] == '0':
e10 = ''
e01 = trans[num_str[1]] # Grabs the corresponding dictionary element for e01 position
elif num_str[1] == '0':
e10 = trans[num_str[0]] + '-shi' # Grabs the corresponding dictionary element for e10 position
e01 = ''
else:
e10 = trans[num_str[0]] + '-shi'
e01 = ' ' + trans[num_str[1]]
return e10 + e01
except Exception as e:
print('Invalid input')
编辑:添加了一些例外情况