将嵌套元组转换为嵌套列表

时间:2017-09-16 04:58:53

标签: python python-2.7 list tuples

I/P - (('1', (('2355', '5'), 'F')),
       ('1', (('2300', '4'), 'M')),
       ('1', (('2400', '5'), 'F')))
O/P - [['1','2355','5','F'],
       ['1','2300','4','M'],
       ['1','2400','5','F']]

我能够获得第一个元素,但其他元素仍然被提取为元组,而我希望所有元素都作为列表的一部分出现。基本上,我希望每个元素都作为列表的一部分单独出现。

4 个答案:

答案 0 :(得分:1)

在3.3+中有一个递归的习惯用法,可以修改它来展平“任何'”的嵌套元组。深度(参见:系统递归限制)

def yielder(x):
    for y in x:
        if isinstance(y, tuple):
            yield from yielder(y)
        else:
            yield y

然后可以在列表理解中使用

[[*yielder(e)] for e in IP]
Out[48]: [['1', '2355', '5', 'F'], ['1', '2300', '4', 'M'], ['1', '2400', '5', 'F']]

我通过在https://jugad2.blogspot.in/2014/10/flattening-arbitrarily-nested-list-in.html的评论中搜索' python flatten'找到了上述内容

对于2/7 http://joedicastro.com/aplanar-listas-en-python.html有食谱,我修改了:

def flat_slice ( lst ):
    lst = list ( lst )
    for i , _ in enumerate ( lst ):
        while ( hasattr ( lst [ i ], "__iter__" ) and not isinstance ( lst [ i ], basestring )):
             lst [ i : i + 1 ] = lst [ i ]
    return lst

(我必须将basetring更改为str为3 +)

它以相同的结果运行

[[*flat_slice(e)] for e in IP]
Out[66]: [['1', '2355', '5', 'F'], ['1', '2300', '4', 'M'], ['1', '2400', '5', 'F']]

答案 1 :(得分:0)

def flaten(t,level=0):
   l = []
   for t1 in t:
     if type(t1) is tuple:
       if level == 0:
         l.append(flaten(t1,level+1))
       else:
         l.extend(flaten(t1,level+1))
     else:
       l.append(t1)
   return l

t = (('1', (('2355', '5'), 'F')), ('1', (('2300', '4'), 'M')), ('1', (('2400', '5'), 'F')))
l = flaten(t)
print(l)

答案 2 :(得分:0)

我将它保存为一个简单的递归例程,也可用于理解:

def unpack(element, stack):
    if isinstance(element, basestring):
        stack.append(element)
    else:
        for i in element:
            unpack(i, stack)
    return stack

[unpack(row, []) for row in IP]

输出:

[['1', '2355', '5', 'F'], ['1', '2300', '4', 'M'], ['1', '2400', '5', 'F']]

答案 3 :(得分:0)

迭代每个iterable,展平所有元素,然后将iterable重新转换为列表。这有两种方法:

<强>鉴于

iterables = (
    ('1', (('2355', '5'), 'F')),
    ('1', (('2300', '4'), 'M')),
    ('1', (('2400', '5'), 'F'))
)

expected = [
    ['1','2355','5','F'],
    ['1','2300','4','M'],
    ['1','2400','5','F']
]

<强>代码

来自this post的修改后的flatten(兼容Python 2/3):

# Approach 1
from collections import Iterable


def flatten(items):
    """Yield items from any nested iterable"""
    for x in items:
        if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
            for i in flatten(x):
                yield i
        else:
            yield x

actual = [list(flatten(i)) for i in iterables]
assert actual == expected

对于单行,请考虑more_itertools.collapse,这个工具也可以展平嵌套的迭代:

# Approach 2
import more_itertools as mit


actual = [list(mit.collapse(i)) for i in iterables]
assert actual == expected

注意:more_itertools是第三方库,它实现了多个itertools recipes和有用的工具。按pip install more_itertools安装。