promotion image of download ymail app
Promoted

Urgent Python Question?

I have two albums shown as lists within lists in a photo below. First of all, I want to add the times of each song together from the first album using Python 3.8. The times of each song are always the final item in each song list. And each of the song lists in the first album are in one big album list. Then I want to display this total as final list inside the first album list. It should read, [Total Album Time: (and then total time in minutes:seconds format, like 83:26)] Then I want to make program which creates list of five shortest songs from each album in one list, sorted from shortest to longest. Then I want to display total time for this new soundtrack as final item in the new list. How do I do this?

Attachment image

1 Answer

Relevance
  • 2 months ago
    Favourite answer

    You can get the last element in a list simply with listname[-1].  That's a shorthand for listname[len(listname) - 1] that you won't find in most other programming languages.

    Your time is a string in "mm:ss" format.  I'd write a function to convert that to an integer number of seconds:

    def to_seconds(mmss):

        mm, ss = mmss.split(':')

        return int(mm)*60 + int(ss)

    That splits the input string into the minutes and seconds parts, converts those pieces to integers and caluclates an integer number of seconds.

    You can convert an integer number of seconds back into string "mm:ss" format with another function.  There are a bunch of ways to do this; but you specified "Python 3.8", so I'll use the new "format string" syntax:

    def to_mmss(sec):

          return F'{sec//60}:{sec%60:02d}'

    Other ways include the old-fashioned (but still supported) % operator:

        '%d:%02d' % (sec//60, sec%60)

    ...or the .format string method:

        '{0}:{1:02d}'.format(sec//60, sec%60)

    ...or the format built-in function with string concatenation:

        str(sec//30) + ':' + format(sec, '02d')

    The common thing in all of those is the '02d' format specification for the seconds, that says:

         'd' : format in base 10 (decimal)

         '2' : minimum result width is 2

         '0' : pad with zeroes instead of spaces

    That's how to_mmss(123) gets "2:03" instead of "2:3" or "2: 3".

    Once you have the times in seconds format, you can add the times, compare them, sort a list with them; just like you would with any other numeric field.  For example, to print the total of all track times in an album:

        total = sum(to_seconds(track[-1]) for track in album)

        print( "Total time:", to_mmss(total))

    That should get you started.

    • ZAB2 months agoReport

      Thank you so much for your help! May you have a long, happy, prosperous life! You rock!

    • Commenter avatarLog in to reply to the answers
Still have questions? Get answers by asking now.