gpt4 book ai didi

python - 查找对象可以转换为哪些其他 python 类型?

转载 作者:太空狗 更新时间:2023-10-30 00:10:09 24 4
gpt4 key购买 nike

作为一个简单的例子,假设一个实用方法,它接受一个 python 对象 input_objout_type,一个 python type 来转换(将对象类型转换为

def convert_obj(input_obj,out_type):

-例子

convert_obj('2','int')
#returns 2
convert_obj([1,2,3],'tuple')
#returns (1,2,3)

该方法只支持特定类型的对象,如str、list、tuple,然后检查是否可以转换为指定的out_type。这是方法中的规则手册:

 supported_conversions = {
tuple: [str, list, set],
str: [tuple, float, list, long, int, set],
float: [str, long, int],
list: [tuple, str, set],
long: [str, float, int],
dict: [tuple, str, list, set],
int: [str, float, long],
set: [tuple, str, list],

}

supported_conversions 中的键是 input_obj 允许的类型。

问题:除了在所有可能的 python 类型列表上使用 try/except 来转换每种类型的样本对象,然后查看哪些是有效的,例如根据 [list,dict,tuple,int,tuple,set] 检查 str 转换在给定键的情况下,python 中是否有更好的方法来生成字典 supported_conversions

注意:类型转换的其他异常将被忽略。例如"1"可以转换为整数 1,但 "XYZ"不能。但这还是表示 str->int 是一个有效的可能转换。

最佳答案

我认为问题空间定义不够明确,无法存在这种方法。有些转变是破坏性的,有些转变可能以不止一种方式发生。几个例子:

>>> list(set([1,2,2,3]))
[1, 2, 3]
>>> list("hello")
['h', 'e', 'l', 'l', 'o']
>>> ["hello"]
['hello']
>>> list({'a':1, 'b': 2})
['a', 'b']
>>> list({'a':1, 'b': 2}.iteritems())
[('a', 1), ('b', 2)]

为了论证,您还可以使用 eval() 将字符串转换为基本上任何 Python 类型。

所以,基本上,这完全取决于您的用例。

如果你真的想做更详尽的搜索,你可以使用types模块来获取内置类型的列表,然后尝试交叉转换(假设你可以获取实例每一个):

>>> import types
>>> [types.__dict__.get(t) for t in dir(types) if t.endswith('Type')]
[<type 'bool'>, <type 'buffer'>, <type 'builtin_function_or_method'>, <type 'builtin_function_or_method'>, <type 'classobj'>, <type 'code'>, <type 'complex'>, <type 'dictproxy'>, <type 'dict'>, <type 'dict'>, <type 'ellipsis'>, <type 'file'>, <type 'float'>, <type 'frame'>, <type 'function'>, <type 'generator'>, <type 'getset_descriptor'>, <type 'instance'>, <type 'int'>, <type 'function'>, <type 'list'>, <type 'long'>, <type 'member_descriptor'>, <type 'instancemethod'>, <type 'module'>, <type 'NoneType'>, <type 'NotImplementedType'>, <type 'object'>, <type 'slice'>, <type 'str'>, <type 'traceback'>, <type 'tuple'>, <type 'type'>, <type 'instancemethod'>, <type 'unicode'>, <type 'xrange'>]

不过,我不知道您是否需要事先生成您的 supported_conversions 字典。假设您总是通过 outtype(intype_value)intype 转换为 outtype,您可以尝试这样做,然后更新映射 (intype , outtype) -> bool,因此如果第一次失败,它不会再次尝试转换。

关于python - 查找对象可以转换为哪些其他 python 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34652591/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com