在Python中,总是返回一个元组的简单方法是,有问题的变量是否包含元组或包含至少一个元组的列表?
# (3, 5) would return (3, 5)
#
# [(3, 5), [200, 100, 100]] would return (3, 5)
#
# [[100, 100, 100], (3, 5)] would return (3, 5)
#
# [(3, 5), (4, 7)] would return (3, 5)
答案 0 :(得分:3)
如果我实际上需要这样的东西,我会做类似的事情:
def first_tuple(t):
return t if isinstance(t,tuple) else next(x for x in t if isinstance(x,tuple))
演示:
>>> first_tuple((3,5))
(3, 5)
>>> first_tuple([(3, 5), [200, 100, 100]])
(3, 5)
>>> first_tuple([[100, 100, 100], (3, 5)])
(3, 5)
>>> first_tuple([(3, 5), (4, 7)])
(3, 5)
>>> first_tuple([[],[]])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in first_tuple
StopIteration
一般来说,你不需要这样的东西。恕我直言,这似乎可能是一个糟糕的设计,这里的数据结构应该重新考虑。