从嵌套子列表返回八进制模式

时间:2019-07-19 08:20:17

标签: python python-3.x list

如何从python列表创建下面描述的模式,或者从numpy数组创建更容易的模式。

假设我有这样一个列表列表:

[
[a,a,0,a],
[0,b,0,b],
[c,0,c,c]
]

返回的列表应按遍历顺序遍历嵌套列表(子列表1的元素1,子列表2的元素1等),但始终创建​​八倍的列表大小。

[
 [a,0,c,0,0,0,0,0],
 [a,b,0,0,0,0,0,0],
 [0,0,c,0,0,0,0,0],
 [a,b,c,0,0,0,0,0]
]

在下一个示例中,子列表中还有另一个子列表:

[
 [a,a,    0,   a],
 [0,[b,b],0,   b],
 [c,c    ,c,[c,c]]
]

结果模式应再次遍历。此处的规则是将子列表中的元素列表中的一个元素处理相同,但对于元素子列表中的两个元素,仅考虑具有深度的元素并将它们用于八进制模式。

[
 [a,0,c, 0,0,0,0,0],
 [a,b,c, 0,0,0,0,0],
 [0,b,0, 0,0,0,0,0],
 [0,0,c, 0,0,0,0,0],
 [a,b,c, 0,0,0,0,0],
 [0,0,c, 0,0,0,0,0],
]

另一个例子:

[
 [a    ,a     ] ,
 [b    ,[b,b,b]],
 [[c,c],0     ]
]

[
[a,b,c,0,0,0,0,0],
[0,0,c,0,0,0,0,0],
[a,b,0,0,0,0,0,0],
[0,b,0,0,0,0,0,0],
[0,b,0,0,0,0,0,0]
]

如果子列表的长度不同:

[
 [a,0],
 [b,[b,b],b]
]

[
 [a,b,0,0,0,0,0,0],
 [0,b,0,0,0,0,0,0],
 [0,b,0,0,0,0,0,0],
 [0,b,0,0,0,0,0,0]
]

有人可以向我展示一种方法,该方法如何处理遍历并使用嵌套列表处理那些异常并返回总是八进制的吗? 可能还有另一个容器或结构使这些模式更易于接收吗?

预先感谢

1 个答案:

答案 0 :(得分:3)

以下是我解决问题的方法:

from functools import reduce

original = [
    ['a', 0],
    ['b', ['b', 'b'], 'b']
]

max_len = max([len(i) for i in original])
padded_original = [
    (i + [0] * max_len)[:max_len]
    for i in original
]
print(padded_original)
# [['a', 0, 0], ['b', ['b', 'b'], 'b']]

max_col_lens = reduce(
    lambda a, b: [max(a[i], b[i]) for i in range(len(a))],
    [
        [len(xi) if isinstance(xi, list) else 1 for xi in x]
        for x in padded_original
    ]
)
print(max_col_lens)
# [1, 2, 1]


original_transformed = [
    reduce(
        lambda a, b: a + b,
        [(item + [0] * size)[:size] for (item, size) in row]
    ) for row in [
        zip(
            [xi if isinstance(xi, list) else [xi] for xi in x],
            max_col_lens
        ) for x in padded_original
    ]
]
print(original_transformed)
# [['a', 0, 0, 0], ['b', 'b', 'b', 'b']]

result_list = [
    [0 for i in range(8)]
    for j in range(
        sum(
            reduce(
                lambda a, b: [max(a[i], b[i]) for i in range(len(a))],
                [
                    [len(xi) if isinstance(xi, list) else 1 for xi in x]
                    for x in padded_original
                ]
            )
        )
    )
]
print(result_list)
# [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]

# rotating transformed_original_transformed
for i in range(len(original_transformed)):
    for j in range(len(original_transformed[i])):
        result_list[j][i] = original_transformed[i][j]

print(result_list)
# [['a', 'b', 0, 0, 0, 0, 0, 0], [0, 'b', 0, 0, 0, 0, 0, 0], [0, 'b', 0, 0, 0, 0, 0, 0], [0, 'b', 0, 0, 0, 0, 0, 0]]