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

如何将输入的字符串列表转换为Python类型转换函数列表?

解决输入类型字符串转转换函数列表的问题

你可以通过两种方式将输入的类型字符串转换为对应的内置转换函数:

方法一:利用全局命名空间(简单直接)

Python的globals()函数可以获取当前全局作用域中的变量和函数,直接通过字符串名称就能拿到对应的类型转换函数:

input_casts = input("Enter the casts: ")
casts = [globals()[cast] for cast in input_casts.split()]

比如输入str str int int float,会得到[str, str, int, int, float]。

方法二:自定义类型映射(更安全)

如果想避免输入未知字符串引发错误,可以提前定义一个允许的类型映射字典,只处理指定的类型:

# 定义支持的类型映射
allowed_casts = {
    'str': str,
    'int': int,
    'float': float
    # 可按需添加其他类型,比如'bool': bool
}

input_casts = input("Enter the casts: ")
casts = [allowed_casts[cast] for cast in input_casts.split()]

可选:添加异常处理

如果担心用户输入不支持的类型,可以加入异常处理,避免程序崩溃:

allowed_casts = {'str': str, 'int': int, 'float': float}
input_casts = input("Enter the casts: ")
casts = []

for cast_name in input_casts.split():
    try:
        casts.append(allowed_casts[cast_name])
    except KeyError:
        print(f"忽略不支持的类型:{cast_name}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 18:39:53