You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中检查列表是否包含任意字符串?

如何在中位数计算前检查列表中的非数值字符串

原代码

import statistics
import time

def medianextra (numlist=[0], i=2):
    Attempt=0
    while not i==0:
        try:
            if not len(numlist)==1:
                try:
                    a = statistics.median(numlist)
                    b = statistics.median_low(numlist)
                    c = statistics.median_high(numlist)
                    print(f"The Median is: {a}")
                    if a != b or a != b:
                        print(f"The Low Median is: {b}")
                        print(f"The High Median is: {c}")

                except BaseException:
                    print("The values are not a numerical number.")    
                except:
                    print("An error occured. Please make sure the values are numerical.")
                break
            elif len(numlist)==(0):
                print("No values detected.")
                break
            elif len(numlist)==(1):
                s = [str(integer) for integer in numlist]
                a_string = "".join(s)
                res = int(a_string)
                print(f"Only one value entered. Median is: {res}")
                break
            else:
                print("An error occured. Please make sure the values are numerical, or values are included.")
                break
            
        except:
            Attempt=Attempt+1
            print("")
            print("Catastrophic failure.")
            print(f"Retrying calculations. Attempt:{Attempt}")
            print(f"Remaining attempts: {i-1}")
            i=i-1
            time.sleep(2)
            if i==0:
                print("\nAttempts failed.\n")
            continue
        
    exit()

问题描述

当传入的numlist包含无法转换为数值的字符串(比如直接传入DataFrame,或是从Excel读取的列中混有非数值字符串)时,程序会错误执行或抛出异常。需要在函数开头的指定位置加入检查逻辑,提前拦截这类无效数据并终止计算。

解决方案

在函数开头的<**HERE**>位置插入以下检查逻辑(若代码已外部导入pandas可省略重复导入):

import pandas as pd  # 已导入则可删除此行

def medianextra (numlist=[0], i=2):
    # 新增:检查列表中的非数值元素
    # 处理pandas Series输入,转为普通列表
    numlist = numlist.tolist() if hasattr(numlist, 'tolist') else numlist
    
    has_invalid = False
    for item in numlist:
        # 跳过空值(如pandas的NaN)
        if pd.isna(item):
            continue
        # 检查字符串类型元素是否可转为数值
        if isinstance(item, str):
            try:
                float(item)
            except ValueError:
                has_invalid = True
                break
        # 检查非字符串的非数值类型元素
        elif not isinstance(item, (int, float)):
            has_invalid = True
            break
    
    if has_invalid:
        print("列表中存在无法转换为数值的元素,请检查数据。")
        exit()
    
    # 原函数剩余代码
    Attempt=0
    while not i==0:
        # ... 原代码内容保持不变

逻辑说明

  • 先处理pandas Series类型的输入,转为普通列表避免遍历异常
  • 遍历每个元素:
    • 跳过空值(如NaN,属于float类型,不影响中位数计算)
    • 对字符串类型元素尝试转换为数值,失败则标记为无效
    • 直接拦截非数值、非可转换字符串的其他类型元素
  • 一旦检测到无效元素,直接打印提示并终止程序,避免后续错误计算

内容的提问来源于stack exchange,提问作者Alireza Ghaffarian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 02:50:34