我有一本包含重复值的字典。
Deca_dict = {
"1": "2_506",
"2": "2_506",
"3": "2_506",
"4": "2_600",
"5": "2_600",
"6": "1_650"
}
我使用了 collections.Counter 来计算每个集合的数量。
decaAdd_occurrences = {'2_506':3, '2_600':2, '1_650':1}
然后我创建了一个新的要更新的值字典。
deca_double_dict = {key: value for key, value in Deca_dict.items()
if decaAdd_occurrences[value] > 1}
deca_double_dict = {
"1": "2_506",
"3": "2_506",
"2": "2_506",
"4": "2_600"
}
(在本例中,它是没有最后一项的原始字典)
我试图弄清楚如何增加 num,使 counter_dict 的值减 1。这将更新除 1 之外的所有值,该值可以保持不变。目标输出允许其中一个重复项保持相同的值,而其余的值字符串的第一个数字将逐渐递增(基于重复计数的数量)。我正在尝试为原始 Deca_dict 表示的数据实现唯一值。
Goal output = {'1':'3_506', '2':'4_506', '3':'2_506', '4':'3_600', '5':'2_600'}
我开始按照以下方式处理事情,但最终只是增加了所有双项,导致我最初拥有的内容,除了值加一之外。对于上下文:原始 Deca_dict 的值被发现连接两个数字(deca_address_num 和 deca_num_route)。此外,homesLayer 是一个 QGIS 矢量图层,其中 deca_address_num 和 deca_num_route 存储在索引为 d_address_idx 和 id_route_idx 的字段中。
for key in deca_double_dict.keys():
for home in homesLayer.getFeatures():
if home.id() == key:
deca_address_num = home.attributes()[d_address_idx]
deca_num_route = home.attributes()[id_route_idx]
deca_address_plus = deca_address_num + increment
next_deca_address = (str(deca_address_plus) + '_' +
str(deca_num_route))
if not next_deca_address in Deca_dict.values():
update_deca_dbl_dict[key] = next_deca_address
结果是没用:
Update_deca_dbl_dict = {
"1": "3_506",
"3": "3_506",
"2": "3_506",
"5": "3_600",
"4": "3_600"
}
我的第二次尝试尝试添加一个计数器,但东西放在了错误的位置。
for key, value in deca_double_dict.iteritems():
iterations = decaAdd_occurrences[value] - 1
for home in homesLayer.getFeatures():
if home.id() == key:
#deca_homeID_list.append(home.id())
increment = 1
deca_address_num = home.attributes()[d_address_idx]
deca_num_route = home.attributes()[id_route_idx]
deca_address_plus = deca_address_num + increment
next_deca_address = (str(deca_address_plus) + '_' +
str(deca_num_route))
#print deca_num_route
while iterations > 0:
if not next_deca_address in Deca_dict.values():
update_deca_dbl_dict[key] = next_deca_address
iterations -= 1
increment += 1
UPDATE尽管下面的答案之一适用于增加字典中的所有重复项目,但我正在尝试重新编写我的代码,因为我需要将这个比较条件与原始数据进行比较才能增加。我仍然得到与第一次尝试相同的结果(无用的结果)。
for key, value in deca_double_dict.iteritems():
for home in homesLayer.getFeatures():
if home.id() == key:
iterations = decaAdd_occurrences[value] - 1
increment = 1
while iterations > 0:
deca_address_num = home.attributes()[d_address_idx]
deca_num_route = home.attributes()[id_route_idx]
deca_address_plus = deca_address_num + increment
current_address = str(deca_address_num) + '_' + str(deca_num_route)
next_deca_address = (str(deca_address_plus) + '_' +
str(deca_num_route))
if not next_deca_address in Deca_dict.values():
update_deca_dbl_dict[key] = next_deca_address
iterations -= 1
increment += 1
else:
alpha_deca_dbl_dict[key] = current_address
iterations = 0