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

标签 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']]

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

最佳答案

在 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

(对于 3+,我必须将 basestring 更改为 str)

运行结果相同

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

关于python - 将嵌套元组转换为嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46250215/

相关文章:

python - 为什么Python的sqlite3模块不尊重位置参数的顺序?

python - 如何将光照应用于 pyopengl 上的 .obj 文件

python - 获取列表 [1,1,2,2,..] 并将其添加到数据框的列中

python - django 模板中的逗号分隔列表

python - 用字符串周围的引号编写 csv (Python)

Python:为什么列表理解比for循环慢

python-2.7 - 如何在 Paho-MQTT 中添加代理设置?

python - 不在python中写入文件

python - 计算矩阵中一个点与所有其他点之间的距离

c# - List<T> 中的 Contains 和 Exists 有什么不同?