Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
index errors
#4
What you want to do is called flattening
import random

m = [[[random.randint(0,4) for i in range(2)] for k in range(4)] for i in range(3)]
print(m)

def flatten(matrix):
    flat = []
    for dim1 in matrix:
        for dim2 in dim1:
            for element in dim2:
                flat.append(element)
    return flat

print(flatten(m))
and that flattening can be coded as one line
def flatten(matrix):
    return [element for dim1 in matrix for dim2 in dim1 for element in dim2]
Reply


Messages In This Thread
index errors - by ridgerunnersjw - Sep-14-2019, 06:42 PM
RE: index errors - by micseydel - Sep-14-2019, 07:15 PM
RE: index errors - by ridgerunnersjw - Sep-14-2019, 08:02 PM
RE: index errors - by ThomasL - Sep-14-2019, 09:10 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020