Python Forum

Full Version: How to use a list of floats
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
When I tried append() it said I can't do that to a tuple. So not a list. But, I still get a float error when trying enumerate().

I'm trying simplify the code to less lines.
We assume that 'total' is defined as a list. How becomes a tuple?


total = []
I'm not sure. I borrowed the code for converting bytes to MB. There was no total=[] outside of it, but when I add it in, I still get the float error. Below, total and s are the same, but both give errors.

    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
You try to iterate a single value. Doesn't matter where you've got the code from
As and addition to what @wavic say,there are bad stuff in this code.
Never use range(len(something),not gone give up on this Dodgy
Also overwrite of the original filepaths,you are getting back byte size so do not call it filepaths.
So look at this:
# Bad
import os

filepaths = ['E:/1py_div/uni.txt', 'E:/1py_div/h.py', 'E:/1py_div/cloud9.txt']
for i in range(len(filepaths)):
    filepaths[i] = os.path.getsize(filepaths[i])

print(filepaths) # [22, 190, 42043]
# Good
import os

filepaths = ['E:/1py_div/uni.txt', 'E:/1py_div/h.py', 'E:/1py_div/cloud9.txt']
file_byte_size = []
for index,item in enumerate(filepaths):
    file_byte_size.append(os.path.getsize(item))

print(file_byte_size) #[22, 190, 42043]
Ahh come to think of this,it's easy to forget the the easiest solution.
# Best
import os

filepaths = ['E:/1py_div/uni.txt', 'E:/1py_div/h.py', 'E:/1py_div/cloud9.txt']
file_byte_size = []
for item in filepaths:
    file_byte_size.append(os.path.getsize(item))

print(file_byte_size) #[22, 190, 42043]
list comprehension is also okay.
import os

filepaths = ['E:/1py_div/uni.txt', 'E:/1py_div/h.py', 'E:/1py_div/cloud9.txt']
file_byte_size = [os.path.getsize(item) for item in filepaths] #[22, 190, 42043]
Pages: 1 2