第5章-11 字典合並 (40分)(考察數字與字符串的混合排序的處理)


字典合並。輸入用字符串表示兩個字典,輸出合並后的字典,字典的鍵用一個字母或數字表示。注意:1和‘1’是不同的關鍵字!

輸入格式:

在第一行中輸入第一個字典字符串 在第二行中輸入第二個字典字符串

輸出格式:

在一行中輸出合並的字典,輸出按字典序。"1"的ASCII嗎為49,大於1,排序時1在前,"1"在后,其它的也一樣。

輸入樣例1:

在這里給出一組輸入。例如:

{1:3,2:5} {1:5,3:7} 
 

輸出樣例1:

在這里給出相應的輸出。例如:

{1:8,2:5,3:7} 
 

輸入樣例2:

在這里給出一組輸入。例如:

{"1":3,1:4} {"a":5,"1":6} 
 

輸出樣例2:

在這里給出相應的輸出。例如:

{1:4,"1":9,"a":5}
第一版(代碼死板,不建議參考,見第二版)
# 字典合並
# Author: cnRick
# Time  : 2020-4-10
dict1 = eval(input())
dict2 = eval(input())
keys1 = dict1.keys()
keys2 = dict2.keys()
minLenFlag = 1 if len(dict1) > len(dict2) else 0
if minLenFlag == 0:
    for i in keys1:
        if i in dict2:
            dict2[i] = dict2[i] + dict1[i]
        else:
            dict2[i] = dict1[i]
    keys = list(dict2.keys())
    keys.sort(key = lambda x: ord(x) if type(x)==str else x)
    cnt = 0
    print("{",end="")
    for i in keys:
        if type(i) == int:
            print("{:d}:{:d}".format(i,dict2[i]),end="")
            cnt += 1
        elif type(i) == str:
            print('"{:s}":{:d}'.format(i,dict2[i]),end="")
            cnt += 1
        if cnt != len(dict2):
            print(",",end="")
    print("}",end="")
        
else:
    for i in keys2:
        if i in dict1:
            dict1[i] = dict1[i] + dict2[i]
        else:
            dict1[i] = dict2[i]
    keys = list(dict1.keys())
    keys.sort(key = lambda x: ord(x) if type(x)==str else x)
    cnt = 0
    print("{",end="")
    for i in keys:
        if type(i) == int:
            print("{:d}:{:d}".format(i,dict1[i]),end="")
            cnt += 1
        elif type(i) == str:
            print('"{:s}":{:d}'.format(i,dict1[i]),end="")
            cnt += 1
        if cnt != len(dict1):
            print(",",end="")
    print("}",end="")

第二版

 1 # 字典合並-簡化版
 2 # Author: cnRick
 3 # Time  : 2020-4-10
 4 dict1 = eval(input())
 5 dict2 = eval(input())
 6 for key in dict2.keys():
 7     dict1[key] = dict1.get(key,0) + dict2[key]
 8 
 9 items_list = list(dict1.items())
10 items_list.sort(key=lambda item:ord(item[0]) if type(item[0]) == str else item[0])
11 print(str(dict(items_list)).replace(" ","").replace("'",'"'))

思路借鑒:https://blog.csdn.net/qq_43479432/article/details/105009411

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM