强制Python函数返回“tuple”类型

2024-09-30 22:14:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了一个似乎解决不了的有趣问题。我有一个相当复杂的系统,它调用一个格式化工具,它被定义为我们支持的每种格式的一个类。类名是动态确定的,并且值的格式是基于我们客户机的API POST文档。在

我遇到的问题是,有些值需要一个键/值对(key, value),而有些值需要多个对,我将其放入元组列表[(key1, value1), (key2, value2)]。在

我需要做的是获取键/值,并创建一个元组的元组并将其传递给传递。我不能用字典,因为以后排序可能很重要。在

这段代码的整体结构相当庞大,为了便于阅读,我将尝试将其分解成小块。在

调用函数:

def map_lead(self, lead):
    mapto_data = tuple()
    for offer_field in self.offerfield_set.all():
        field_name = offer_field.field.name
        if field_name not in lead.data:
            raise LeadMissingField(lead, field_name)

        formatted_list = format_value(offer_field.mapto, lead.data[field_name])

        if type(formatted_list).__name__ == 'list':
            for item in formatted_list:
                mapto_data += (item,)

        elif type(formatted_list).__name__ == 'tuple':
            mapto_data += (formatted_list)
        return mapto_data

示例格式\u type1:

^{pr2}$

示例格式\u类型2:

@staticmethod
def do_format(key, value):
    if len(value) > 3:
        value = value[:3] + '-' + value[3:]
        if len(value) > 7:
            value = value[:7] + '-' + value[7:]
    return key, value

我试图将example_format_type2的返回值显式定义为元组:

@staticmethod
def do_format(key, value):
    if len(value) > 3:
        value = value[:3] + '-' + value[3:]
        if len(value) > 7:
            value = value[:7] + '-' + value[7:]
    formatted_value = tuple()
    formatted_value += (key, value)
    return formatted_value

但不管我做什么,它似乎都被解释为calling_function中的一个列表。在

所以,我总是得到type(formatted_list).__name__ == 'list'。因此,如果它是一个元组,我将返回for循环遍历元组中的每个项,并将其作为一个值添加到mapto_data元组中。在

有没有一种方法可以强制Python从example_format_type2返回值,以便它在calling_function中解释为元组?在

编辑1:

原来问题出在map_lead中,我在那里添加了mapto_data元组。我漏掉了后面的逗号。在


Tags: keynameformatfielddatalenifvalue
2条回答

example_format_type2确实返回一个元组,我很确定错误是在其他地方。类似于format_value函数。请注意,如果将元组添加到带有+=的列表中,结果将是一个列表:

>>> a = [1, 2]
>>> a += (3, 4)
>>> print a
[1, 2, 3, 4]

还要考虑使用以下语法检查formatted_list的类型:

^{pr2}$

我相信你可以只返回一个元组文本(idk,如果这是所谓的)?在

>>> def test():
...     return (1, 2)
... 
>>> thing = test()
>>> thing
(1, 2)
>>> type(thing)
<type 'tuple'>
>>> type(thing).__name__
'tuple'

相关问题 更多 >