python:扁平化为列表列表但仅此而已

标签 python

我有一个列表列表,它嵌套在多层列表中。

可能的输入:

[[[[1,2,3] , [a,b,c]]]][[[1,2,3] , [a,b, c]]][[[1,2,3]] , [[a,b,c]]]

当我使用 flat() 时,它只会展平所有不是我想要的东西。

[1,2,3,a,b,c]

我需要的是

[[1,2,3] , [a,b,c]]

作为最终输出。

我的平面定义如下

def flat(S):
    if S == []:
        return S
    if isinstance(S[0], list):
        return flat(S[0]) + flat(S[1:])
    return S[:1] + flat(S[1:])

最佳答案

import collections
def is_listlike(x):
    return isinstance(x, collections.Iterable) and not isinstance(x, basestring)

def flat(S):
    result = []
    for item in S:
        if is_listlike(item) and len(item) > 0 and not is_listlike(item[0]):
            result.append(item)
        else:
            result.extend(flat(item))
    return result

tests = [ [[[[1,2,3] , ['a','b','c']]]],
          [[[1,2,3] , ['a','b','c']]],
          [[[1,2,3]] , [['a','b','c']]] ]

for S in tests:
    print(flat(S))

产量

[[1, 2, 3], ['a', 'b', 'c']]
[[1, 2, 3], ['a', 'b', 'c']]
[[1, 2, 3], ['a', 'b', 'c']]

关于python:扁平化为列表列表但仅此而已,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27652422/

相关文章:

python - Keras:每个时期的混淆矩阵

python - Matplotlib : the colorbar keeps shrinking

python - Matplotlib bar() 函数总是引发错误

python - 检查字典键是否在字典列表(元组)中

python - 如何从命令行安装 DMG 文件?

python - 在正则表达式匹配后获取部分数据以替换原始字符串

python - hyperledger indy-sdk 和 Libvcx 有什么区别?

python - 为什么我有时会在使用 SQS 客户端时出现 Key Error

python - 当目标函数有多个参数时如何使用 scipy.optimize minimize_scalar?

python - 如何异步获取子进程的标准输出数据?