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
  Why is the copy method name in python list copy and not `__copy__`? YouHoGeon 2 282 Apr-04-2024, 01:18 AM
Last Post: YouHoGeon
  Copy List Not Copying BAbdulBaki 3 630 Aug-19-2023, 02:03 AM
Last Post: perfringo
  About list copy. water 3 1,555 Apr-03-2022, 02:42 AM
Last Post: deanhystad
Question Making a copy list in a function RuyCab 1 1,804 Jul-11-2021, 02:06 PM
Last Post: Yoriz
  List structure lost when multiplying Protonn 2 2,255 Apr-23-2020, 04:16 AM
Last Post: buran
  Transform list or set regardless of nesting structure blubb 2 1,970 Mar-10-2020, 07:17 PM
Last Post: ibreeden
  Most efficient way of reshaping a list-array structure midarq 2 2,070 Sep-25-2019, 09:32 AM
Last Post: midarq
  copy list into variable poroton 1 2,605 Aug-10-2018, 07:19 AM
Last Post: Gribouillis
  Copy List [Help Needed] Patricamillie 0 2,225 Jun-11-2018, 10:53 AM
Last Post: Patricamillie
  How to use list (structure) in the SQL Select command? pyuser1 2 2,935 Apr-27-2018, 02:33 PM
Last Post: pyuser1

Forum Jump:

User Panel Messages

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