Search code examples
pythonlistfloor

Python: Remove numbers with the same floor function from a list


I have this list

x = [1.1, 1.2, 1.2, 2.1, 2.2, 3.0, 4.5]

I want to delete the numbers with same floor function and get the first number of each integers as:

x = [1.1, 2.1, 3.0, 4.5] 

I tried

x = [1.1, 1.2, 1.2, 2.1, 2.2, 3.0, 4.5]
def h(l): 
    y = []
    for i in l: 
        if int(i) != int(i+1):
            z = i 
            y.append(z) 
    return(y)
print(h(x))

But when I print it yields the same result as the list


Solution

  • You can use itertools.groupby if x is not sorted sort it first

    out = [next(g) for k, g in itertools.groupby(x, floor)]
    out
    # [1.1, 2.1, 3.0, 4.5]