在 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)
如果我真的需要这样的东西,我会做这样的事情:
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
一般来说,你不应该需要这样的东西。恕我直言,这似乎是一个糟糕的设计,应该重新考虑这里的数据结构。