This seems to be working for me with that type of dataset:
# Separate lists of device, then lists of code/distance
data1 = ["A", ["1", 100], ["2", 350], ["3", 200]]
data2 = ["B", ["4", 250], ["5", 50], ["6", 10]]
data3 = ["C", ["7", 200], ["8", 1], ["9", 999]]
# Total data set
data = [data1, data2, data3]
# Max distance of 300
maxDistance = 300
# Closest devices
devicesClosest, sources = [],[]
# For each sub-list of data...
for d in data:
# Extract source item
source = d[0]
sources.append(source)
# Get targets (all but source)
targets = d[1:]
# Arbitrarily large distance, no device by default
minDistance = 999999999
minDevice = None
# For each target for that device...
for t in targets:
# Get the device and distance
device = t[0]
distance = t[1]
# If the distance is less than minimum and max...
if distance < minDistance and distance < maxDistance:
# It becomes the new minimum device/distance
minDevice = device
minDistance = distance
# Append the device if found (otherwise None)
devicesClosest.append(minDevice)
# Print the outcome
print(sources)
print(devicesClosest)
If you want to exclude devices as you go (only use once per item) it is much harder, you would need to build a list of ‘used’ devices to ensure you skip any that have already been used so far. Something more like this…
# Separate lists of device, then lists of code/distance
data1 = ["A", ["1", 100], ["2", 350], ["3", 10]]
data2 = ["B", ["1", 250], ["2", 50], ["3", 10]]
data3 = ["C", ["1", 200], ["2", 1], ["3", 10]]
# Total data set
data = [data1, data2, data3]
# Max distance of 300
maxDistance = 300
# Closest devices
devicesClosest, sources, devicesUsed = [],[],[]
# For each sub-list of data...
for d in data:
# Extract source item
source = d[0]
sources.append(source)
# Get targets (all but source)
targets = d[1:]
# Arbitrarily large distance, no device by default
minDistance = 999999999
minDevice = None
# For each target for that device...
for t in targets:
# Get the device and distance
device = t[0]
distance = t[1]
# If the distance is less than minimum and max...
if distance < minDistance and distance < maxDistance:
if device not in devicesUsed:
# It becomes the new minimum device/distance
minDevice = device
minDistance = distance
# Append the device if found (otherwise None)
devicesClosest.append(minDevice)
devicesUsed.append(minDevice)
# Print the outcome
print(sources)
print(devicesClosest)
print(devicesUsed)
You will run into the classic issue of having to determine how to fairly ‘pair’ devices in a suitable order. This might require instead working across all devices per source within 300 that have not been used yet instead of in sub-sets per source.
Maybe look into bird tools Sparrow package which has a point pairing algorithm in it of this nature.