0

I have an list which tells me which columns need to be converted from bytes into KB.

covert_to_kb_columns=[9, 10, 21, 22, 24]

I am having trouble implementing my code correctly. I want to check that if I am on the an 'idx' number that matches one of the numbers in the covert_to_kb_columns list than I should preform the calculation otherwise leave the number as is. The try/except statement is for when there is no number in the file just a '', so I append a zero.

print covert_to_kb_columns
for idx, column_number in enumerate(columns_I_am_working_with):
    print idx
    #Check if I need to convert number from bytes to KB
    if idx == [number for number in covert_to_kb_columns]:
        print "Need to divide by 1024.0"
        data_to_use.append("{:.1f}".format(float(row[column_number]) / 1024.0))
    #Otherwise just append number as is
    else:
        try:
            float(row[column_number])
            data_to_use.append(row[column_number])
        except ValueError:
            data_to_use.append('0')

My print statements give me this result: (Note '.' is to indicate that all numbers were printed but I'm not writing them all 39 numbers out )

[9, 10, 21, 22, 24]
0
1
2
3
.
.
.
9
10
.
.
.
21
22
23
24
.
.
.
39

It seems that it never enters the print statement to perform the conversion. I think the issue is with the line

if idx == [number for number in covert_to_kb_columns]:

But I can't spot what I doing wrong

Catherine
  • 727
  • 2
  • 11
  • 30

2 Answers2

2

idx == [number for number in covert_to_kb_columns] checks if the index is equal to a list containing all of the elements of covert_to_kb_columns. It's the same as idx == covert_to_kb_columns.

All you need to do is idx in covert_to_kb_columns.

Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67
0

Your if condition is false. The right is:

if idx in covert_to_kb_columns:

[number for number in covert_to_kb_columns] build a new list from your list covert_to_kb_columns. And they are identical. It is useless here.

And with idx == [number for number in covert_to_kb_columns] you are comparing a index number with a list. This condition returns always the value false

qvpham
  • 1,896
  • 9
  • 17