【问题标题】:Conversion of types of objects对象类型的转换
【发布时间】:2022-01-29 14:59:29
【问题描述】:

如何在 python 上编写一个函数,在输入中接受两个对象并在输出时给出两个对象都可以呈现的最小类型?

示例:我们有两个对象:15.25。我们无法将它们都转换为 int,因为这样我们将丢失有关 5.25 的信息,这些信息将被转换为 5。我们可以将它们都转换为float1.05.25,这是正确的答案。当然我们可以说我们可以将它们都转换为str"1""5.25",但在我们的解释中,我们假设int < float < tuple < list < str(当然我们不能比较对象的类型,但我们假设得到答案)然后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()

但是当我比较intfloat 时,答案是int 但应该是float,我不知道如何解决。

【问题讨论】:

  • isinstance(_type(x), _type) 毫无意义,要么引发异常,要么是True
  • @mkrieger1 但那我该如何解决呢?
  • 如果你想测试x 是否已经属于给定类型,我认为你应该改用isinstance(x, _type),而不是它是否可以转换为那个类型.
  • @mkrieger1 它不起作用。我试过了
  • 那你还有一个问题。

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


【解决方案1】:

如果我很好理解您的问题,您希望获得可以匹配两个变量的最小/最佳类型。

我已将您的排名顺序更新为int < float < str < tuple < list,但如果您愿意,您仍然可以保持排名。所以这里有一个函数,它接受几个变量作为参数,并返回匹配这些变量的最小类型的名称:

def type_convertion(*variables):
    data_types = {'int': 0, 'float': 1, 'str': 2, 'tuple': 3, 'list': 4} # types and their rankings
    minimum_type = [0, ''] # this list will contain the ranking and the name of the minimum type
    for variable in variables:
        variable_type = type(variable).__name__ # get the name of the variable type
        if variable_type not in data_types:
            # if the type is not reconized we can always convert it in str
            return 'str'
        if data_types[variable_type] > minimum_type[0]:
            # if the variable type is of higher rank from the previous one then change the minimum variable
            minimum_type = [data_types[variable_type], variable_type]
    return minimum_type[1]

*variables 允许您为函数提供任意数量的参数,因此您不限于 2 个变量。

要获得最小类型,请像这样调用函数:

>>> type_convertion('a', 10, 0.5)
'str'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多