如何从python中的结果中删除额外的列表

时间:2022-08-01 21:42:22

Result has extra brackets, how can I remove them in python?

结果有额外的括号,如何在python中删除它们?

I am calling two methods where one returns a tuple of dictionaries and the second returns a list of tuples of dictionaries.

我正在调用两个方法,其中一个返回一个字典元组,第二个返回一个字典元组列表。

print method_A() // ({'id': 6}, {'id': 9})
print method_B() // [({'id': 6}, {'id': 9})]

How can I remove the list from the result of second method?

如何从第二种方法的结果中删除列表?

I tried it with type checking and has worked but I want to know if there is any easy to way to do it.

我尝试了类型检查并且已经工作但我想知道是否有任何简单的方法来做到这一点。

I tried following code:

我试过以下代码:

resultA = method_A() // ({'id': 6}, {'id': 9})
resultB method_B() // [({'id': 6}, {'id': 9})]

if type(resultA) == list:
    resultA = resultA[0]
if type(resultB) == list:
    resultB = resultB[0]

or directly I can use resultB[0] if I know it

或直接我可以使用resultB [0]如果我知道它

1 个解决方案

#1


If one of these methods always returns a list with the tuple element, just use indexing:

如果其中一个方法总是返回带有元组元素的列表,那么只需使用索引:

resultA = method_A()
resultB = method_B()[0]

If either method sometimes returns a list object and sometimes just the tuple, use a function:

如果任一方法有时返回列表对象,有时只返回元组,请使用函数:

def unwrap(v):
    v[0] if isinstance(v, list) else v

and use that:

并使用:

resultA = unwrap(method_A())
resultB = unwrap(method_B())

Then contact whomever created those methods and talk to them sternly about consistency in API design.

然后联系那些创建这些方法的人,并严格地与他们讨论API设计的一致性。

#1


If one of these methods always returns a list with the tuple element, just use indexing:

如果其中一个方法总是返回带有元组元素的列表,那么只需使用索引:

resultA = method_A()
resultB = method_B()[0]

If either method sometimes returns a list object and sometimes just the tuple, use a function:

如果任一方法有时返回列表对象,有时只返回元组,请使用函数:

def unwrap(v):
    v[0] if isinstance(v, list) else v

and use that:

并使用:

resultA = unwrap(method_A())
resultB = unwrap(method_B())

Then contact whomever created those methods and talk to them sternly about consistency in API design.

然后联系那些创建这些方法的人,并严格地与他们讨论API设计的一致性。