adyo4552 adyo4552 - 2 years ago 97
Python Question

Python: Find distance between identical elements within a list

Say I have a list such as:

[a, b, c, c, b, a, b, c, a]

I want to write a function that will return:

[-, -, -, 1, 3, 5, 2, 4, 3]

Note that I only need distance to (most proximal) previous occurrence, hence the initial dashes in the output.

Answer Source

Assuming the elements in original_list are hashable you could do it as follows:

def distance_list(original_list, first_val='-'):
    last_occurence = {}
    distances = []

    for pos, elem in enumerate(original_list):
        if elem in last_occurence:
            distances.append(pos - last_occurence[elem])
        last_occurence[elem] = pos

    return distances
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download