我遇到了一个似乎解决不了的有趣问题。我有一个相当复杂的系统,它调用一个格式化工具,它被定义为我们支持的每种格式的一个类。类名是动态确定的,并且值的格式是基于我们客户机的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
元组。我漏掉了后面的逗号。在
example_format_type2
确实返回一个元组,我很确定错误是在其他地方。类似于format_value
函数。请注意,如果将元组添加到带有+=的列表中,结果将是一个列表:还要考虑使用以下语法检查
^{pr2}$formatted_list
的类型:我相信你可以只返回一个元组文本(idk,如果这是所谓的)?在
相关问题 更多 >
编程相关推荐