3D列表意味着我们需要制作一个包含三个参数的列表,即(A x b x c),就像其他语言中的3D数组一样。在这个程序中,我们将尝试形成一个三维列表,其内容为“#”。让我们看看以下例子:
null
Input : 3 x 3 x 3 Output : [[['#', '#', '#'], ['#', '#', '#'], ['#', '#', '#']], [['#', '#', '#'], ['#', '#', '#'], ['#', '#', '#']], [['#', '#', '#'], ['#', '#', '#'], ['#', '#', '#']]] Input : 5 x 3 x 2 Output : [[['#', '#', '#', '#', '#'], ['#', '#', '#', '#', '#'], ['#', '#', '#', '#', '#']], [['#', '#', '#', '#', '#'], ['#', '#', '#', '#', '#'], ['#', '#', '#', '#', '#']]]
# Python program to print 3D list # importing pretty printed import pprint def ThreeD(a, b, c): lst = [[ [ '#' for col in range (a)] for col in range (b)] for row in range (c)] return lst # Driver Code col1 = 5 col2 = 3 row = 2 # used the pretty printed function pprint.pprint(ThreeD(col1, col2, row)) |
输出:
[[['#', '#', '#', '#', '#'], ['#', '#', '#', '#', '#'], ['#', '#', '#', '#', '#']], [['#', '#', '#', '#', '#'], ['#', '#', '#', '#', '#'], ['#', '#', '#', '#', '#']]]
参考 pprint() 来深入了解这个话题。
现在假设我们需要将两个3D列表合并为一个。
# Python program to merge two 3D list into one # importing pretty printed import pprint def ThreeD(a, b, c): lst1 = [[ [ '1' for col in range (a)] for col in range (b)] for row in range (c)] lst2 = [[ [ '2' for col in range (a)] for col in range (b)] for row in range (c)] # Merging using "+" operator lst = lst1 + lst2 return lst # Driver Code col1 = 3 col2 = 3 row = 3 # used the pretty printed function pprint.pprint(ThreeD(col1, col2, row)) |
输出:
[[['1', '1', '1'], ['1', '1', '1'], ['1', '1', '1']], [['1', '1', '1'], ['1', '1', '1'], ['1', '1', '1']], [['1', '1', '1'], ['1', '1', '1'], ['1', '1', '1']], [['2', '2', '2'], ['2', '2', '2'], ['2', '2', '2']], [['2', '2', '2'], ['2', '2', '2'], ['2', '2', '2']], [['2', '2', '2'], ['2', '2', '2'], ['2', '2', '2']]]
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END