RedShift
RedShift

Reputation: 273

Python: Split list into list of lists

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.

Upvotes: 1

Views: 2193

Answers (3)

pooya
pooya

Reputation: 153

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 

Upvotes: 1

Kryštof Řeháček
Kryštof Řeháček

Reputation: 2483

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([])

Upvotes: 0

hausdork
hausdork

Reputation: 821

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)]]

Upvotes: 1

Related Questions