我有一个字典,里面有一个键,每个键都有很多值:
d={'POU': ['GL', '1', '999', '4646']
'TSA': ['LA', '2', '888', '4545']
'RAS': ['NA', '5', '565', '1316']
'TSO': ['RA', '7', '575', '1376']}
每个键的第二个值表示距离 (1, 2, 5, 7( 以 km 为单位。按键根据距离排序。
我想比较以下密钥的距离,并丢弃彼此靠近且距离等于或小于 1km 的密钥。 所以最终的字典将是:
d={'POU': ['GL', '1', '999', '4646']
'RAS': ['NA', '5', '565', '1316']
'TSO': ['RA', '7', '575', '1376']}
如何做到这一点?
到目前为止,我设法做的只是根据距离限制键,例如:
if (float(d[key][1])<10):
但我无法将每个键的值与以下键的值进行比较。我是蟒蛇的菜鸟,最近两天我一直在为它疯狂。
您可以循环访问键,并在条件匹配时将其删除。
# save keys in a list
vals = list(d.keys())
## count keys
dict_len = len(vals)
# save keys to be removed
to_rmv = []
# iterate through keys
for i in range(dict_len):
for j in range(i+1, dict_len):
p = int(d[vals[j]][1])- int(d[vals[i]][1]) ## second index is distance
if p <= 1:
to_rmv.append(vals[j])
## remove keys
for k in to_rmv:
del d[k]
## see output
print(d)
{'POU': ['GL', '1', '999', '4646'],
'RAS': ['NA', '5', '565', '1316'],
'TSO': ['RA', '7', '575', '1376']}
keys_to_remove = []
for k1, v1 in d.items():
for k2, v2 in d.items():
if k1 == k2:
continue
dist1 = float(v1[1])
dist2 = float(v2[1])
if abs(dist1 - dist2) <= 1:
keys_to_remove.append(k2)
result = d.copy()
for k in keys_to_remove:
result.pop(k)
print(result)