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

Dhr*_*hak 6 python

举一个简单的例子,假设一个实用方法,它接受一个python对象input_obj,并且out_type,一个python type将该对象转换(类型转换)为

def convert_obj(input_obj,out_type):
Run Code Online (Sandbox Code Playgroud)

-例子

convert_obj('2','int')
#returns 2
convert_obj([1,2,3],'tuple')
#returns (1,2,3)
Run Code Online (Sandbox Code Playgroud)

该方法仅支持特定类型的对象,如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],

    }
Run Code Online (Sandbox Code Playgroud)

其中的键supported_conversions是input_obj的允许类型.

问题:除了在所有可能的python类型的列表上使用try/except来转换每种类型的样本对象,然后查看有效的内容,例如检查str[list,dict,tuple,int,tuple,set]的转换是有一个更好的方法在python中生成dict supported_conversions,给它的键?

注意:要忽略类型转换的其他异常.例如,"1"可以转换为整数1,但"XYZ"不能.但这仍然意味着str-> int是一种有效的可能转换.

Vla*_*lad 3

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

>>> 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)]
Run Code Online (Sandbox Code Playgroud)

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

所以,基本上,这一切都取决于您的用例。

如果您确实想做更详尽的搜索,您可以使用该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'>]
Run Code Online (Sandbox Code Playgroud)

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