Search code examples
pythonpandaslistspotipy

Create new list in sequence of lists if previous list exceeds item threshold


I'm using the Spotify API to add tracks to a series of playlists in chronological order based on date first added (to an external set of playlists) such that:

  • Playlists are named Playlist #1, Playlist #2, Playlist #3, etc
  • Each playlist contains 100 tracks (list items)
  • Once a current playlist reaches 100 items, a new playlist is created and further items are added to that playlist and so on.

An example would be:

From the API I am getting 244 tracks that need to be sorted into playlists.

Playlist #4 already has 70 tracks and thus needs to be filled with 30 tracks.

Playlist #5 does not exist so it needs to be created and filled with 100 tracks.

Playlist #6 is filled with 100 tracks.

Playlist #7 is filled with the remaining 14 tracks.

Is there a way to automate this flow?

I have managed to get some code to generate the playlist names in a sequence:

lst = ['Playlist #1', Playlist #2', 'Playlist #3', 'Playlist #4']
lst1 = max(lst, key=lambda x: int(x.split('#', 1)[1]))
highest_number = int(lst1.split("#")[1]) + int(1)
new_number = "Playlist #" + str(highest_number)
new_number --> Playlist #5
lst.append(new_number)
lst

Not sure how to think about this problem, so any help would be much appreciated.


Solution

  • I managed to find a solution to the first part of the problem of getting new list names in sequence - It's not pretty but it works:

    lst = ['Playlist #5', 'Playlist #2', 'Playlist #3', 'Playlist #4']
    lst1 = max(lst, key=lambda x: int(x.split('#', 1)[1]))
    highest_number = int(lst1.split("#")[1]) + int(1)
    new_number = "Playlist #" + str(highest_number)
    new_number
    lst.append(new_number)
    lst
    

    Will post the second part of the solution once I get there!