Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to use a list of floats
#1
How can make a list of floats useful if you can't iterate through them?

I've tried things like: 
        
    fred = ', '.join(total)
    fred = map(float, fred)

    fred = [float(x) for x in total]
    fred = list(map(float, total))

    newlist = []
    for i in total:
        tok = i.split(total)
        for num in total:
            newlist.append(float(tok[num]))
        total.append(newlist)
I tried changing them to strings to iterate through then change them back to do math, but that didn't work either.
Reply
#2
You can iterate over a list of floats without a problem. If you're trying to str.join() a list of floats, that's not going to work because the collection passed to str.join() must contain strings.

Can you show with a runnable snippet what exactly the problem you're having is?
Reply
#3
This asks for a file path and returns the size of only avi files in the folder. I need to do further math with these numbers, which is where I am stuck. Things in """ section and # areas are things I've rotated in to try but all give errors about not being able to interate through floats.

from Tkinter import *
import os
import math

root = Tk()
root.title("DVD Calculator")

spinbox1 = Spinbox(root, values= ("SD", "HD"), wrap = TRUE)
spinbox1.grid(row=0, column=1, padx=105, pady=15)

lbl1 = Label(root, text="File Path", width=8)
lbl1.grid(row=2, column=2, pady=15, sticky=W)           
       
entry1 = Entry(root, justify= RIGHT, width=55)
entry1.grid(row=2, column=1, pady=15)

def reset():
    entry1.delete(0, END)


global file_path
global total

def file_size():
    """
    this function will return the file size
    """
    file_path = entry1.get()
    filepaths = []
        
    #gets list of avi    
    for basename in os.listdir(file_path): 
        filename = os.path.join(file_path, basename)
        if not filename.endswith(('.mov', '.AVI', '.avi')): continue
        if os.path.isfile(filename):
            filepaths.append(filename)

    # Re-populate list with size, convert to GB
    for i in xrange(len(filepaths)):
        filepaths[i] = (os.path.getsize(filepaths[i]))
        nums = filepaths[i]
        i = int(math.floor(math.log(nums, 1024)))
        p = math.pow(1024, i)
        s = round(nums/p, 2)
        total = s
#        fred = [float(x) for x in total]
#        fred = list(map(float, total))
        print s
        
        fred = ', '.join(s)
        fred = map(float, fred)
        print fred
'''        
#change list for can iterate thru floats
    newlist = []
    for i in total:
        tok = i.split(total)
        for num in total:
            newlist.append(float(tok[num]))
        total.append(newlist)
    print newlist
            
            first = s[0:] * .20
            print first
       
            if type(i)== float:
                newlist.append(i)
                print newlist              

    def frange(total, end=None, inc=None):
        "A range function, that does accept float increments..."

        if end == None:
            end = total + 0.0
            start = 0.0

        if inc == None:
            inc = 1.0

        L = []
        while 1:
            next = total + len(L) * inc
            if inc > 0 and next >= end:
                break
            elif inc < 0 and next <= end:
                break
            L.append(next)
            
        print frange(total)

'''        
resetButton = Button(root, text="Reset", command= reset)
resetButton.grid(row=4, column=1, pady=100)

calcButton = Button(root, text="Calculate", command=file_size)
calcButton.grid(row=4, column=2)
        

root.geometry("450x350+200+100")
root.mainloop()
Reply
#4
Can you reproduce your problem without any GUI code? Just hard-code the list you're having problems with and then the few lines that reproduce your problem. The whole snippet should be runnable and no larger than 5-10 lines.
Reply
#5
Stripping out the GUI still gives the error:
Error:
Traceback (most recent call last):   File "C:\Users\kb\Desktop\Python\test2.py", line 36, in <module>     for fred in total: TypeError: 'float' object is not iterable
import os
import math


global file_path
global total

file_path = raw_input("location: ")
filepaths = []
    
#gets list of avi    
for basename in os.listdir(file_path): 
    filename = os.path.join(file_path, basename)
    if not filename.endswith(('.mov', '.AVI', '.avi')): continue
    if os.path.isfile(filename):
        filepaths.append(filename)

# Re-populate list with size, convert to GB
for i in xrange(len(filepaths)):
    filepaths[i] = (os.path.getsize(filepaths[i]))
    nums = filepaths[i]
    i = int(math.floor(math.log(nums, 1024)))
    p = math.pow(1024, i)
    s = round(nums/p, 2)
    total = s
    print total
    
count = 0
for fred in total:
    fred= (s * .20)
    if fred > 4.5:
        count = count +1
print count
Reply
#6
You can iterate over total if it is a list, tuple, string or dictionary. You assign to it a single variable.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#7
I guess you see clear if i do this.
>>> total = 9.0
>>> type(total)
<type 'float'>

>>> for fred in total:
...     print(fred)
...     
Traceback (most recent call last):
 File "<interactive input>", line 1, in <module>
TypeError: 'float' object is not iterate
As mention bye wavic,
total need to an Iterable or maybe an integer then it can be used with range().
Reply
#8
I need the accuracy of the float numbers so I can't round them to integers.

Wavic: Do you mean something like:
total = list(s)
I tried that and still got a float error.
Reply
#9
Can you post code that is max 5-10 lines? You shouldn't need imports, functions, I/O (e.g. files or raw_input()) or the global keyword, just hard-code around your problem anything that itself is not your problem.
Reply
#10
Assuming total is defined as a list.

....

# Re-populate list with size, convert to GB
for i in xrange(len(filepaths)):
    filepaths[i] = (os.path.getsize(filepaths[i]))
    nums = filepaths[i]
    i = int(math.floor(math.log(nums, 1024)))
    p = math.pow(1024, i)
    s = round(nums/p, 2)
    total.append(s)
    print s

.....
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  When is it safe to compare (==) two floats? Radical 4 713 Nov-12-2023, 11:53 AM
Last Post: PyDan
  floats 2 decimals rwahdan 3 1,625 Dec-19-2021, 10:30 PM
Last Post: snippsat
  rounding and floats Than999 2 3,103 Oct-26-2020, 09:36 PM
Last Post: deanhystad
  int, floats, eval menator01 2 2,431 Jun-26-2020, 09:03 PM
Last Post: menator01
  Stuck comparing two floats Tizzle 7 3,021 Jun-26-2020, 08:23 AM
Last Post: Tizzle
  rounding floats to a number of bits Skaperen 2 2,315 Sep-13-2019, 04:37 AM
Last Post: Skaperen
  comparing fractional parts of floats Skaperen 4 3,357 Mar-19-2019, 03:19 AM
Last Post: casevh
  Integer vs Floats Tazbo 2 2,873 Jan-09-2019, 12:06 PM
Last Post: Gribouillis
  Formatting floats Irhcsa 6 4,157 Oct-04-2018, 04:23 PM
Last Post: volcano63
  How do you sort a table by one column?? (of floats) sortedfunctionfails 3 12,296 Jan-11-2018, 09:04 AM
Last Post: sortedfunctionfails

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020