在任何可能包含或可能包含元组的内容中找到第一个元组?

时间:2013-03-10 19:04:58

标签: python list parsing tuples

在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)

1 个答案:

答案 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

一般来说,你不需要这样的东西。恕我直言,这似乎可能是一个糟糕的设计,这里的数据结构应该重新考虑。