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

如何实现检测tuple元组内所有元素是否为相同类型的函数

同类型判断函数实现

核心逻辑

取第一个传入参数的类型作为基准,遍历其余所有参数逐一比对类型即可,空输入的返回值可根据自身需求调整,以下实现默认空输入返回True。

代码实现

def auto(*args):
    if not args:
        return True
    base_type = type(args[0])
    return all(type(arg) == base_type for arg in args)

测试验证

# 测试用例1:元素类型不同
print(auto('red', 42, {1,2,3})) # 输出 False

# 测试用例2:元素类型均为字符串
print(auto('red', "aa", "hgbnj")) # 输出 True

补充说明

如果需要支持子类匹配(比如认为bool类型属于int子类也算匹配),可以将代码中的type(arg) == base_type替换为isinstance(arg, base_type)即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 04:15:03