如何用while循环与if-else输出Python中所有符合条件的结果?
解决多条件输出所有符合结果的问题
你的问题出在elif的互斥逻辑上——它只会执行第一个满足条件的分支,所以无法输出所有符合要求的结果。不需要用while循环,用以下两种方法就能解决:
方法1:打包检查项用for循环遍历
把每个需要检查的DataFrame变量和对应的提示文本打包成列表,逐个判断输出:
# 将变量与对应提示配对 check_items = [ (high, 'High level is Red'), (med, 'Medium level is Red'), (low, 'Low level is Red'), (grand_total, 'Grand Total is Red') ] has_match = False # 遍历所有检查项 for df, msg in check_items: # 从单值DataFrame中提取数值(如果是多值需根据需求调整) if df.item() >= 0.20: print(msg) has_match = True # 没有符合条件的情况 if not has_match: print('None')
方法2:使用独立的if语句
直接为每个条件写独立的if判断,放弃elif的互斥逻辑:
has_match = False if high.item() >= 0.20: print('High level is Red') has_match = True if med.item() >= 0.20: print('Medium level is Red') has_match = True if low.item() >= 0.20: print('Low level is Red') has_match = True if grand_total.item() >= 0.20: print('Grand Total is Red') has_match = True if not has_match: print('None')
补充说明
- 因为你的变量是独立DataFrame,需要用
.item()(适用于单值DataFrame)提取数值进行判断;如果是多值DataFrame,可根据需求改用.any()(任意值符合)或.all()(所有值符合)来判断。 while循环在这里完全没必要,上述两种方法更简洁直接,能确保所有符合条件的结果都被输出。
内容的提问来源于stack exchange,提问作者Crystal
相关产品推荐
相关产品推荐

