📜  Python|创建 3D 列表

📅  最后修改于: 2022-05-13 01:54:25.978000             🧑  作者: Mango

Python|创建 3D 列表

3-D 列表意味着我们需要创建一个包含三个参数的列表,即 (axbxc),就像其他语言中的 3D 数组一样。在这个程序中,我们将尝试形成一个内容为“#”的 3-D 列表。让我们看看以下这些例子:

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