-
胡子哥哥
使用map和听写理解:dct = {"a": [100, 200, 300], "b": [-100, 200, 100]}def changer(number): char = "D" if number > 100 else "DI" return f"{char}{number}"new_dct = {key: list(map(changer, values)) for key, values in dct.items()}print(new_dct)输出{'a': ['DI100', 'D200', 'D300'], 'b': ['DI-100', 'D200', 'DI100']}
-
萧十郎
def dict_change(dicto): modified_dict = {} for key,value in dicto.items(): key_tuple = tuple((('D' if no>100 else 'DI')+ str(no) for no in key)) modified_dict[key_tuple] = value return modified_dictold_dict = {(110, 12, 13, 14, 15, 101): 'ba', (12, 126, -127, 128): 'pa'}print(dict_change(old_dict))输出{('D110', 'DI12', 'DI13', 'DI14', 'DI15', 'D101'): 'ba', ('DI12', 'D126', 'DI-127', 'D128'): 'pa'}
-
冉冉说
这是最紧凑的单行方式:src = {(11, 12, 13, 14, 15, 16): 'ba', (125, 126, 127, 128): 'pa'}d_out = {tuple(['Di','D'][i>100]+ str(i) for i in k):v for k,v in src.items()}print(d_out)Out[1]:{('Di11', 'Di12', 'Di13', 'Di14', 'Di15', 'Di16'): 'ba', ('D125', 'D126', 'D127', 'D128'): 'pa'}说清楚在这种情况下,如果i less than or equal 100给 ['DI','D'][i>100]你['DI','D'][False]解释为['DI','D'][0]并返回'DI'在这种情况下,如果i great than 100给 ['DI','D'][i>100]你['DI','D'][True]解释为['DI','D'][1]并返回'D'