cwl
cwl

Reputation: 204

Why is my if statement testing floating point values always false?

import xlrd

file_path = r"C:\Users\Allen\Desktop\数据曲线.xlsx"
table = xlrd.open_workbook(file_path).sheet_by_index(2)
data_current = table.col_values(4)[1:]
data_time = table.col_values(2)[1:]
time_start = []
for i in data_current:
    index = data_current.index(i)
    if float(i) < 0.1 and float(data_current[index+1]) > 1:
        print('come on!')
    else:
        print('a')

My input:

data_current = ['0.0', '0.0', '1.44']

This is just an example, but the real data follows the same structure.

Why is my output always a, and never come on!?

Upvotes: 0

Views: 34

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122412

data_current.index(i) will return the first match, so for '0.0' index is always going to be 0.

Use the enumerate() function to provide a running index instead:

for index, i in enumerate(data_current):

Take into account that index + 1 can be outside of the range of valid indices.

Upvotes: 1

Related Questions