1

Suppose that I have list:

list = [(4, 7), (3, 7), (5, 7), (4, 6), (4, 8), (2, 7), (3, 6), (3, 8), (6, 7)]

That I want to divide the list into sublists of lengths: [2, 3, 4] (these lengths can vary)

To produce: sublist_list = [[(4, 7), (3, 7)],[(5, 7), (4, 6), (4, 8)], [(2, 7), (3, 6), (3, 8), (6, 7)]]

What's the quickest way that I can do this? Thanks in advance.

3 Answers 3

1
myList = [(4, 7), (3, 7), (5, 7), (4, 6), (4, 8), (2, 7), (3, 6), (3, 8), (6, 7)]

listOfLengths = [2, 3, 4]

def getSublists(listOfLengths,myList):
    listOfSublists = []
    for i in range(0,len(listOfLengths)):
        if i == 0:
            listOfSublists.append(myList[:listOfLengths[i]])
        else:
            listOfSublists.append(myList[listOfLengths[i-1]:listOfLengths[i-1]+listOfLengths[i]])
    return listOfSublists

Then if you call getSublists on your myList (original list input) and listOfLengths (a list containing the length of your sublists), you get

#In: getSublists(listOfLengths,myList)
#Out: [[(4, 7), (3, 7)], [(5, 7), (4, 6), (4, 8)], [(4, 6), (4, 8), (2, 7), (3, 6)]]
Sign up to request clarification or add additional context in comments.

Comments

1

You can user list[i:j] feature in python which returns a new list contains list[i] to list[j-1] elements of original list.

base = 0
Lengths =[] #list of lengths
for num in Length:
   sub_list.append(List[base:num+base])
   base += num #jump to next length 

1 Comment

While this code may answer the question, it would be better to include some context, explaining how it works and when to use it. Code-only answers are not useful in the long run.
0

What about simply iterating the list and appending to the new lists?

c = 0
for sublist in list:
    sublistlist[len(sublistlist)-1].append(sublist)
    c += 1
    if c % 2:
        sublistlist.append([])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.