pythonrounding

Round-to-floor a list of float numbers?


I want to round the float numbers in a list to floor in python, I tried math.floor([i]), the error is: a float is required and I also tried math.trunc([i]), I received this error: AttributeEror_trunc. I couldb't find any proper code to solve this problem. Any help would be appreciated!

Here is the code that I have so far:

with open ("G:\Speed\\december.sorted.movement.Sample.txt", 'r') as f:
    firs_line = f.readline()
    split=firs_line.split ("\t")

    Speed = [r.split()[5] for r in f]
    Speedf=[]
    for item in Speed:
        Speedf.append(float(item))

    denominator= 8677.8   
    i = [x/denominator for x in Speedf]

    import math
    v= math.floor([i])
    #print v [:5]

Solution

  • math.floor() only accepts a single float value argument (or an object with a __floor__() method). To apply it (or another callable taking a single argument) to a whole list you can use list comprehensions as shown below:

    import math
    
    with open('december.sorted.movement.Sample.txt', 'r') as f:
        first_line = next(f)
        split = first_line.split('\t')
    
        Speeds = [float(line.split()[5]) for line in f]
        denominator = 8677.8
        v = [math.floor(sp / denominator) for sp in Speeds]
        print(v[:5])
    

    If you don't need the Speeds list for anything else, you could even combine the two list comprehensions into one and do things like this (although it's less readable):

    with open('december.sorted.movement.Sample.txt', 'r') as f:
        first_line = next(f)
        split = first_line.split('\t')
    
        denominator = 8677.8
        v = [math.floor(float(line.split()[5] )/ denominator) for line in f]
        print(v[:5])