分析
通过
ord(x[0])
取其 ascii码值。
Python ord() 函数
- 它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值
数字的ascii就是本身,如果遇到字符,则按
ord()
进行排序,因此sorted排序函数需要进行一个if类型判断。
d=sorted(a.items(),key=lambda item:item[0] if type(item[0])==int else ord(item[0]))
题目
解法
自解(存在错误)
输出类型不符合要求,可以看到,如果是字符,最后输出有双引号。
a=eval(input())
b=eval(input())
c={}
for key,value in b.items():
a[key]=a.get(key,0)+value
d=sorted(a.items(),key=lambda item:item[0] if type(item[0])==int else ord(item[0]))#要对类型判断,依据 ord
print("{",end="")
for i in range(len(d)):
print("{}:{}".format(d[i][0],d[i][1]),end="")
if i!=len(d)-1:#遇到最后一个元素,即i==len(d)-1的情况,就不能再输出","
print(",",end="")
else:
print("}")
完善
a=eval(input())
b=eval(input())
for key,value in b.items():
a[key]=a.get(key,0)+value
d=sorted(a.items(),key=lambda item:item[0] if type(item[0])==int else ord(item[0]))
print("{",end="")
for i in range(len(d)):
if type(d[i][0])==int:#判断类型
print("{}:{}".format(d[i][0],d[i][1]),end="")
else:
print('"{}":{}'.format(d[i][0],d[i][1]),end="")
if i!=len(d)-1:#遇到最后一个元素,即i==len(d)-1的情况,就不能再输出","
print(",",end="")
else:
print("}")