Python如何将坐标列表与聚类索引列表映射为按簇编号分组的字典
问题解决代码与说明
错误原因
- 未提前初始化字典中各聚类对应的空列表,直接操作不存在的key触发KeyError
- 用赋值语句
=代替append方法,导致每次覆盖前值,仅保留最后一个元素 - 聚类编号逻辑计算错误,导致生成的key从0开始,不符合从1开始的需求
实现代码
# 输入数据 coords = ['7,16', '71,84', '72,48', '36,52', '75,36', '52,28', '76,44', '11,69', '56,35', '15,21', '32,74', '88,32', '10,74', '61,34', '51,85', '10,75', '55,96', '94,12', '34,64', '71,59', '76,75', '25,16', '54,100', '62,1', '60,85', '16,32', '14,77', '40,78', '2,60', '71,4', '78,91', '100,98', '42,32', '37,49', '49,34', '3,5', '42,77', '39,60', '38,77', '49,40', '40,53', '57,48', '14,99', '66,67', '10,9', '97,3', '66,76', '86,68', '10,60', '8,87'] cluster_index = [3, 2, 3, 3, 3, 3, 3, 1, 3, 3, 2, 3, 1, 3, 2, 1, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 1, 2, 1, 3, 2, 2, 3, 3, 3, 3, 2, 2, 2, 3, 3, 3, 1, 2, 3, 3, 2, 2, 1, 1] # 初始化结果字典,聚类编号从1到3,每个对应空列表 res = { 'cluster_1': [], 'cluster_2': [], 'cluster_3': [] } # 遍历配对的坐标和聚类索引 for coord_str, cid in zip(coords, cluster_index): # 把坐标字符串转成[x,y]整数列表 x, y = map(int, coord_str.split(',')) # 追加到对应聚类的列表里 res[f'cluster_{cid}'].append([x, y]) # 按要求格式输出 for cluster_name, coord_list in res.items(): print(f"{cluster_name}: {', '.join(map(str, coord_list))}")
输出效果
cluster_1: [11, 69], [10, 74], [10, 75], [14, 77], [2, 60], [14, 99], [10, 60], [8, 87] cluster_2: [71, 84], [32, 74], [51, 85], [55, 96], [34, 64], [76, 75], [54, 100], [60, 85], [40, 78], [78, 91], [100, 98], [42, 77], [39, 60], [38, 77], [66, 67], [66, 76], [86, 68] cluster_3: [7, 16], [72, 48], [36, 52], [75, 36], [52, 28], [76, 44], [56, 35], [15, 21], [88, 32], [61, 34], [94, 12], [71, 59], [25, 16], [62, 1], [16, 32], [71, 4], [42, 32], [37, 49], [49, 34], [3, 5], [49, 40], [40, 53], [57, 48], [10, 9], [97, 3]
内容的提问来源于stack exchange,提问作者Samantha Clark
相关产品推荐
相关产品推荐

