Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Copy List Structure
#1
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!
Reply
#2
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)
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
(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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Copy List Not Copying BAbdulBaki 3 574 Aug-19-2023, 02:03 AM
Last Post: perfringo
  About list copy. water 3 1,503 Apr-03-2022, 02:42 AM
Last Post: deanhystad
Question Making a copy list in a function RuyCab 1 1,768 Jul-11-2021, 02:06 PM
Last Post: Yoriz
  List structure lost when multiplying Protonn 2 2,201 Apr-23-2020, 04:16 AM
Last Post: buran
  Transform list or set regardless of nesting structure blubb 2 1,930 Mar-10-2020, 07:17 PM
Last Post: ibreeden
  Most efficient way of reshaping a list-array structure midarq 2 2,030 Sep-25-2019, 09:32 AM
Last Post: midarq
  copy list into variable poroton 1 2,573 Aug-10-2018, 07:19 AM
Last Post: Gribouillis
  Copy List [Help Needed] Patricamillie 0 2,207 Jun-11-2018, 10:53 AM
Last Post: Patricamillie
  How to use list (structure) in the SQL Select command? pyuser1 2 2,891 Apr-27-2018, 02:33 PM
Last Post: pyuser1
  Which approach is better to copy a list? nexusfactor 6 4,641 Oct-15-2017, 10:45 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

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