Python: a unique list with a twist

Let's say I have a list:

L = [15,16,57,59,14]

The list contains mesuprerias that are not very accurate: this is the actual value of the element is + -2 from the recorded value. Thus, 14.15 and 16 can have the same value. What I want to do is a unique list, taking into account addition errors. The output should be like this:

l_out = [15,57]

or

l_out = [(14,15,16),(57,59)]

I have no problem getting the result with a for loop. However, I am curious if there could be a more elegant solution. Ideas have been tested a lot.

+5
source share
4 answers

As Lazir noted in the comments, a similar issue was posted here . Using the cluster module, the solution to my problem would be:

>>> from cluster import *
>>> L = [15,16,57,59,14]
>>> cl = HierarchicalClustering(L, lambda x,y: abs(x-y))
>>> cl.getlevel(2)
[[14, 15, 16], [57, 59]]

( ):

>>> [mean(cluster) for cluster in cl.getlevel(2)]
[15, 58]
+5

lib python, itertool groupby :

from itertools import groupby

L = [15,16,57,59,14]

# Stash state outside key function. (a little hacky).
# Better way would be to create stateful class with a __call__ key fn.
state = {'group': 0, 'prev': None}
thresh = 2

def _group(cur):
    """Group if within threshold."""
    if state["prev"] is not None and abs(state["prev"] - cur) > thresh:
        state["group"] += 1 # Advance group
    state["prev"] = cur
    return state["group"]

# Group, then drop the group key and inflate the final tuples.
l_out = [tuple(g) for _, g in groupby(sorted(L), key=_group)]

print l_out
# -> [(14, 15, 16), (57, 59)]
+2

Here's how I would do it with a pure-Python approach:

s = sorted(L)
b = [i + 1 for i, (x, y) in enumerate(zip(s, s[1:])) if y > x + 2]
result = [s[i:j] for i, j in zip([None] + b, b + [None])]

Here bis a list of "gaps", indices, where the cluster ends.

+2
source

For a loop is the easiest way, but if you really need a single-line code:
l_out = list(set(tuple([tuple(filter(lambda i: abs(item - i) < 3, L)) for item in L])))
Very unclear though, I would prefer for a version :)

-1
source

All Articles