Home > front end >  Splitting a nested list in to multiple list using a for loop
Splitting a nested list in to multiple list using a for loop

Time:09-26

I'm quite new to coding and i cannot seam to figure this problem out. I have a nested list

mnd = [
    [0, 0, 0, 0, 0, 1, 2],
    [3, 4, 5, 6, 7, 8, 9],
    [10, 11, 12, 13, 14, 15, 16],
    [17, 18, 19, 20, 21, 22, 23],
    [24, 25, 26, 27, 28, 29, 30],
    [31, 0, 0, 0, 0, 0, 0]
]

How do i split the original list in to smaller lists using a for loop while deliting the last two elements of the nested list. I can do it manually but can not figure it out how to do this in a for loop.

manually the code is this:

w1 = mnd[0]
w2 = mnd[1]
w3 = mnd[2]
w4 = mnd[3]
w5 = mnd[4]
n = 2
del w1[-n:]
del w2[-n:]
del w3[-n:]
del w4[-n:]
del w5[-n:]

How can i simplify this?

CodePudding user response:

you can use indexing and re-assign the values

for indx, w in enumerate(mnd):
    mnd[indx] = w[:-2]

CodePudding user response:

for indx, w in enumerate(mnd): mnd[indx] = w[:-2]

for i in range(1, len(mnd)   1):
    exec(f"w{i}={mnd[i - 1]}")

print(w1,w2,w3,w4,w5)

Gave me the output that i needed. output: [0, 0, 0, 1, 2] [5, 6, 7, 8, 9] [12, 13, 14, 15, 16] [19, 20, 21, 22, 23] [26, 27, 28, 29, 30]

CodePudding user response:

for k, m in enumerate(mnd):
    globals()[f'w{k   1:d}'] = m[:-n]
  • Related