Python | Creación de una lista 3D

Una lista tridimensional significa que necesitamos hacer una lista que tenga tres parámetros, es decir, (axbxc), al igual que una array tridimensional en otros idiomas. En este programa intentaremos formar una Lista 3-D con su contenido como “#”. Veamos estos siguientes ejemplos:

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))

Producción:

[[['#', '#', '#', '#', '#'],
  ['#', '#', '#', '#', '#'],
  ['#', '#', '#', '#', '#']],
 [['#', '#', '#', '#', '#'],
  ['#', '#', '#', '#', '#'],
  ['#', '#', '#', '#', '#']]]

Consulte pprint() para obtener más información sobre este tema.

Ahora supongamos que necesitamos fusionar dos listas 3D en una.

# 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))

Producción:

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

Publicación traducida automáticamente

Artículo escrito por Chinmoy Lenka y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *