Python Forum
Copy List Structure - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Copy List Structure (/thread-16929.html)



Copy List Structure - leoahum - Mar-20-2019

L1 = [[1,2,3],[4,2],[6,8,1],[4,3]]
L2 = [1,2,3,4,5,6,7,8,9,10]

L3 =[]

def ListStrcCopy(L1,L2):
    L = []
    for i in L1:
         L.append (L2.pop(0))
    return L

for i in L1:
    L3.append(ListStrcCopy(i,L2))


print (L3)
I'm trying to copy the list structure from L1 to L2. The new list is [[1, 2, 3], [4, 5], [6, 7, 8], [9, 10]]. The script above achieved the goal, but I'm seeking for a simpler way to do that.

Thanks!


RE: Copy List Structure - ichabod801 - Mar-20-2019

Instead of taking the items off individually, you could take them off in slices:

L1 = [[1,2,3],[4,2],[6,8,1],[4,3]]
L2 = [1,2,3,4,5,6,7,8,9,10]

L3 =[]
start = 0
for sub in L1:
    L3.append(L2[start:(start + len(sub))])
    start += len(sub)



RE: Copy List Structure - leoahum - Mar-22-2019

(Mar-20-2019, 04:09 PM)ichabod801 Wrote: Instead of taking the items off individually, you could take them off in slices:

L1 = [[1,2,3],[4,2],[6,8,1],[4,3]]
L2 = [1,2,3,4,5,6,7,8,9,10]

L3 =[]
start = 0
for sub in L1:
    L3.append(L2[start:(start + len(sub))])
    start += len(sub)

Thanks a lot! I had that idea, but couldn't figure out how to do that in Python.