Python中对字典值内的d标识元素进行升序排序的问题
问题描述
我有一个Python字典,结构如下:
{ 'Term1': [6, 'd3', 'd5', 'd43', 'd4', 'd6', 'd7'], 'Term2': [6, 'd1', 'd15', 'd46', 'd2', 'd3', 'd4'], 'Term3': [6, 'd3', 'd5', 'd43', 'd5', 'd6', 'd77'], 'Term4': [6, 'd1', 'd15', 'd46', 'd16', 'd17', 'd77'], 'Term5': [6, 'd3', 'd5', 'd43', 'd4', 'd10', 'd22'], 'Term6': [6, 'd1', 'd15', 'd46', 'd17', 'd55', 'd77'], 'Term7': [6, 'd3', 'd5', 'd43', 'd2', 'd7', 'd22'], 'Term8': [6, 'd1', 'd15', 'd46', 'd14', 'd66', 'd88'], 'Term9': [6, 'd1', 'd15', 'd46', 'd2', 'd77', 'd88'], 'Term10': [6, 'd3', 'd5', 'd43', 'd4', 'd44', 'd77'], 'Term11': [6, 'd1', 'd15', 'd46', 'd57', 'd66', 'd88'], 'Term12': [3, 'd2', 'd7', 'd66'], 'Term13': [3, 'd4', 'd44', 'd77'], 'Term14': [3, 'd55', 'd66', 'd88'] }
每个键对应的值列表首元素为数字,后续是带d前缀的字符串。我需要将列表中d开头的元素按数字部分升序排序,例如'Term1'对应的值需变为[6, 'd3', 'd4', 'd5', 'd6', 'd7', 'd43']。
我尝试使用以下代码处理:
','.join(sorted(values, key=lambda x: int(x[1:])))
其中values为intermediate_dictionary[term],但出现异常且无法正常工作。以下是我构建self.final_inverted_index的完整代码:
for term in intermediate_dictionary.keys(): intermediate_dictionary[term].insert(0, len(intermediate_dictionary[term])) self.final_inverted_index[term] = intermediate_dictionary[term]
解决方案
问题根源
- 直接对整个
values列表排序会包含首元素的数字,执行x[1:]时会触发TypeError(数字没有切片操作); - 使用
','.join()会将列表转为字符串,但实际需要的是排序后的列表结构; - 先插入长度再排序的顺序错误,应该先排序元素,再计算并插入长度。
修正后的代码
情况1:intermediate_dictionary初始值已包含首元素数字
如果你的intermediate_dictionary里的每个值列表已经有首元素数字(如示例中的结构),需要先提取出d前缀元素排序,再拼接回首元素:
self.final_inverted_index = {} for term, items in intermediate_dictionary.items(): # 提取首元素长度和后续d元素 count = items[0] d_items = items[1:] # 按数字部分升序排序d元素 sorted_d_items = sorted(d_items, key=lambda x: int(x[1:])) # 组合成最终列表 self.final_inverted_index[term] = [count] + sorted_d_items
情况2:intermediate_dictionary初始值只有d前缀元素
如果intermediate_dictionary的原始值列表没有首元素数字(即你是先插入长度再得到示例结构),则调整顺序为先排序再插入长度:
self.final_inverted_index = {} for term, d_items in intermediate_dictionary.items(): # 排序d元素 sorted_d_items = sorted(d_items, key=lambda x: int(x[1:])) # 计算长度并插入头部 sorted_d_items.insert(0, len(sorted_d_items)) self.final_inverted_index[term] = sorted_d_items
验证结果
运行修正后的代码,Term1的结果会变为:[6, 'd3', 'd4', 'd5', 'd6', 'd7', 'd43']
完全符合需求。
内容的提问来源于stack exchange,提问作者Sam Sam
相关产品推荐
相关产品推荐

