删除元组内的parantheses

时间:2017-11-29 14:59:45

标签: python python-3.x list tuples strip

我有一个元组列表:

listoftuples = [(('elementone', 'elementtwo'), 'elementthree')(....

现在我想将此列表输出为:

listoftuples = [('elementone', 'elementtwo', 'elementthree')(....

我如何删除那些额外的parantheses? 我试图剥掉他们放不起作用。

1 个答案:

答案 0 :(得分:0)

如果深度为2,则可以使用itertools:

import itertools
listoftuples = [(('elementone', 'elementtwo'), 'elementthree')]
final_list = [tuple(itertools.chain.from_iterable([i] if not isinstance(i, tuple) else i for i in b)) for b in listoftuples]

输出:

[('elementone', 'elementtwo', 'elementthree')]

但是,对于任意深度,最好使用递归:

def flatten(s):
   if not isinstance(s, tuple):
      yield s
   else:
      for b in s:
          for i in flatten(b):
              yield i


listoftuples = [(('elementone', 'elementtwo'), 'elementthree')]
final_list = map(tuple, map(flatten, listoftuples))

输出:

[('elementone', 'elementtwo', 'elementthree')]