我有一个包含重复值的字典。
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。这将更新所有值,除了一个可以保持不变。目标输出允许其中一个重复项保持相同的值,而其余重复项的值字符串的第一个数字将逐渐递增(基于计数的重复次数)。我试图实现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
更新尽管下面的一个答案适用于递增字典中所有重复的项目,但我正在重新编写我的代码,因为我需要将此比较条件与原始数据进行比较以进行递增。我仍然得到了与第一次尝试(无用的)相同的结果。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
'
或"
就可以了。 - nbrodecaAdd_occurrences
是什么?Deca_dict
和deca_dict
是否应该相同? - Paul Cornelius