-
白猪掌柜的
您可以使用collections.defaultdict、迭代和更新由存储桶边界确定的键。这比创建可变数量的变量更好。d = {(0, 2): 1, (0, 4): 2, (0, 10): 3, (0, 3): 4, (0, 11): 5, (0, 20): 6, (0, 8): 7, (0, 14): 8}L = [0, 5, 10, 15, float('inf')] # include infinite to facilitate later comparisonsfrom collections import defaultdictdd = defaultdict(dict)for k, v in d.items(): for i, j in zip(L, L[1:]): if i <= k[1] < j: dd[i].update({k: v}) breakprint(dd)defaultdict(dict, {0: {(0, 2): 1, (0, 3): 4, (0, 4): 2}, 5: {(0, 8): 7}, 10: {(0, 10): 3, (0, 11): 5, (0, 14): 8}, 15: {(0, 20): 6}})该算法可以通过使用bisect而不是L按顺序迭代边界来改进。
-
潇潇雨雨
当然这可以写得更好,但你应该明白这个想法。只需遍历 dict,并根据您可以动态定义或生成的各种条件检查键的 y 值。thing = { (1,2): 'a', (2,19): 'b'}d1 = {}d2 = {}for k, v in thing.items(): // while iterating through the original dict, write some logic to determine how you want to split up based on the y values. if k[1] < 5: d1[k] = v if k[1] < 10: d2[k] = vprint(d1, d2)
-
梦里花落0921
这应该有效。original_dict = {(0, 2):"a", (0, 4):"b", (0, 10):"c", (0, 3):"d", (0, 11):"e", (0, 20):"f", (0, 8):"g", (0, 14):"h"}thresholds = [0, 5, 10, 15]thresholds = sorted(thresholds,reverse=True)new_dict_of_dicts = {} #threshold: dictfor threshold in thresholds: new_dict_of_dicts[threshold] = {} for key in list(original_dict.keys()): if key[1] > threshold: new_dict_of_dicts[threshold][key] = original_dict.pop(key)print(new_dict_of_dicts) #{15: {(0, 20): 'f'}, 10: {(0, 11): 'e', (0, 14): 'h'}, 5: {(0, 10): 'c', (0, 8): 'g'}, 0: {(0, 2): 'a', (0, 4): 'b', (0, 3): 'd'}}