为何我的if-elif-else语句输出全为相同值?求排查解决
问题描述
我需要对.csv文件中的testResp.keys_raw、location和money列进行多条件判断,为每个受试者的所有单词设置word_value_dict[word]的值:1代表正确,-1代表错误。但目前所有输出结果均为-1,不符合预期。
现有代码如下:
# get correct/incorrect for each word from testTrials.csv word_value_dict = {} try: df = pd.read_csv(s + 'testTrials.csv') with open(s + 'testTrials.csv') as testTrials_file: for row_index, row in df.iterrows(): if pd.isna( row['money'] ) or row['money'] == 'money': continue word = row['word'] money = float( row['money'] ) ISI = float( row['ISI'] ) response = row['testResp.keys_raw'] location = float( row['location']) print(f"{s} : Row {row_index}: Response={response}, Location={location}, Money={money}") # check if the money value corresponds to a correct word if response == 'c' and location == -150 and money == 1: word_value_dict[word] = 1 #correct word elif response == 'a' and location == 150 and money == 1: word_value_dict[word] = 1 #correct word elif response == 'c' and location == -150 and money == 0.01: word_value_dict[word] = 1 #correct word elif response == 'a' and location == 150 and money == 0.01: word_value_dict[word] = 1 #correct word elif response == 'c' and location == 0: word_value_dict[word] = -1 #incorrect word elif response == 'a' and location == 0: word_value_dict[word] = -1 #incorrect word elif response == 'b' and location == 0: word_value_dict[word] = 1 #correct word else: word_value_dict[word] = -1 #invalid value except FileNotFoundError: print(f'File not found for subject: {s} - testTrials.csv') continue if word in word_value_dict.keys(): correct = word_value_dict[word] else: correct = 0 print({correct}, file=fout, end='') except FileNotFoundError: print(f'File not found for subject: {s} - studyTrials.csv')
此前尝试的方法
尝试直接用row['money']做判断,结果还是全为-1:
if response == 'c' and location == -150 and row['money'] == 1: word_value_dict[word] = 1 #correct word elif response == 'a' and location == 150 and row['money'] == 1: word_value_dict[word] = 1 #correct word elif response == 'c' and location == -150 and row['money'] == 0.01: word_value_dict[word] = 1 #correct word elif response == 'a' and location == 150 and row['money'] == 0.01: word_value_dict[word] = 1 #correct word elif response == 'c' and location == 0: word_value_dict[word] = -1 #incorrect word elif response == 'a' and location == 0: word_value_dict[word] = -1 #incorrect word elif response == 'b' and location == 0: word_value_dict[word] = 1 #correct word else: word_value_dict[word] = -1 #invalid value #this just outputted all the values as -1 as well.
尝试把else分支设为None,结果全为None:
else: word_value_dict[word] = None #invalid value #This outputted all the values as None
问题原因及解决方法
核心问题
- 缩进错误:代码中
if word in word_value_dict.keys():及后续打印逻辑不在循环内部,且位于第一个try块之外,导致循环生成的word_value_dict根本没被使用,打印的correct值逻辑完全错误。 - 浮点数精度问题:直接用
==比较money和1、0.01这类浮点数,可能因为CSV读取时的精度损失导致判断不成立。 - 输入值格式问题:
response可能包含多余空格(比如'c '而非'c'),导致字符串匹配失败。
修正后的代码
import math import pandas as pd # get correct/incorrect for each word from testTrials.csv word_value_dict = {} try: df = pd.read_csv(s + 'testTrials.csv') # 不需要重复打开文件,pd.read_csv已经读取了内容 for row_index, row in df.iterrows(): if pd.isna(row['money']) or row['money'] == 'money': continue word = row['word'] money = float(row['money']) # 对response做去空格处理,避免格式问题 response = str(row['testResp.keys_raw']).strip() location = float(row['location']) print(f"{s} : Row {row_index}: Response='{response}', Location={location}, Money={money}") # 用math.isclose处理浮点数比较,避免精度问题 is_money_1 = math.isclose(money, 1.0, rel_tol=1e-9) is_money_001 = math.isclose(money, 0.01, rel_tol=1e-9) is_location_neg150 = math.isclose(location, -150.0, rel_tol=1e-9) is_location_pos150 = math.isclose(location, 150.0, rel_tol=1e-9) is_location_0 = math.isclose(location, 0.0, rel_tol=1e-9) # 简化条件判断 if (response == 'c' and is_location_neg150 and (is_money_1 or is_money_001)) or \ (response == 'a' and is_location_pos150 and (is_money_1 or is_money_001)) or \ (response == 'b' and is_location_0): word_value_dict[word] = 1 elif (response in ['a', 'c'] and is_location_0): word_value_dict[word] = -1 else: word_value_dict[word] = -1 print(f"⚠️ Row {row_index}未匹配任何有效条件:Response='{response}', Location={location}, Money={money}") # 将判断和打印逻辑放到循环内部 correct = word_value_dict.get(word, 0) print(correct, file=fout, end='') except FileNotFoundError: print(f'File not found for subject: {s} - testTrials.csv') continue except Exception as e: print(f'处理subject {s}时出错:{str(e)}')
关键修改点
- 修复缩进,将
correct值的判断和打印逻辑移到循环内部,确保每个行处理后立即输出结果。 - 使用
math.isclose()替代直接==比较浮点数,解决精度问题。 - 对
response做strip()处理,去除前后空格,避免字符串匹配失败。 - 简化条件判断逻辑,减少重复代码,同时增加调试输出,方便定位未匹配条件的行。
- 移除了多余的
with open语句,因为pd.read_csv已经完成了文件读取。
内容的提问来源于stack exchange,提问作者Annie Cooper
相关产品推荐
相关产品推荐

