【问题标题】:Type conversation of objects in pythonpython中对象的类型转换
【发布时间】:2022-01-27 03:31:35
【问题描述】:

如何在 python 上编写一个函数,在输入中接受两个对象并在输出时给出两个对象都可以呈现的最小类型? 例如,如果我们有[1, 2, 3]2,我们可以将其转换为str,如果我们有"Hi"1.2,我们可以将其转换为str,如果我们有True 和@987654328 @我们可以将其转换为float等等。

【问题讨论】:

  • 您能否澄清一下“如果我们有True1.2,我们可以将其转换为float”是什么意思?您的意思是您可以将True 转换为浮点数吗?
  • 这看起来像是一个 x y 问题。你想用它解决什么问题?
  • @ewong 是的。这是对话的最小可能类型。例如,我们可以将它们转换为str,但float小于str,所以答案是float
  • @KlausD。我试着写一些不等式,比如 type(int)
  • 为什么一种类型应该小于另一种类型?

标签: python python-3.x function types type-conversion


【解决方案1】:

Python 中的所有对象都可以转换为字符串,甚至是用户定义的类实例。

>>> class Test:
    pass

>>> t = Test()
>>> str(t)
'<__main__.Test object at 0x0000015315891730>'
>>> str(1)
'1'
>>> str(True)
'True'
>>> str([1, 2, 3])
'[1, 2, 3]'
>>> 

这是因为他们有一个__str__ 函数,即使你没有定义它也会自动定义。

编辑:你可以这样做(请原谅丑陋的代码)

def leastConversions(first, second):
    type_casts = [str, int, float, tuple, list, dict]
    times = {}
    for _type in type_casts:

        if not isinstance(first, _type):
            times[_type] = 0
            try:
                if not isinstance(first, _type):
                    temp = _type(first)
                    times[_type] += 1
            except TypeError:
                del times[_type]
                continue
            
            try:
                if not isinstance(second, _type):
                    temp = _type(second)
                    times[_type] += 1
            except TypeError:
                del times[_type]
                continue
    return min(times, key = lambda k: times[k])

【讨论】:

  • 显然我们可以将其全部转换为str,但问题是:两个对象都可以转换为的最小类型是什么?比如True1.2的答案是float[1, 2](1, 2)的答案是list等等
  • True1.2 的答案也是 str,除非您正在寻找所需的最少转化次数?
  • 我编辑了我的答案,也许这就是你想要的。
  • 但是有问题。我试图用isinstance 做同样的事情,但是当你比较intfloat 时,它会将其转换为int,而不是float。我的尝试较低
【解决方案2】:

当比较 intfloat 时,答案是 int 但应该是 float

def type_convertion(first, second):
    data_types = [int, float, tuple, list, str]
    times = {}
    for _type in data_types:
        times[_type] = 0
        try:
            if isinstance(_type(first), _type):
                times[_type] += 1
        except TypeError:
            del times[_type]
            continue
        try:
            if isinstance(_type(second), _type):
                times[_type] += 1
        except TypeError:
            del times[_type]
            continue
        return times.keys()

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2018-10-13
  • 1970-01-01
  • 2022-12-10
  • 1970-01-01
  • 1970-01-01
  • 2017-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多