Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get a list of tuples from two lists depending on their value and index

date = ['21 Jul 2021', False, False, '18 Jul 2021', False, False, '15 Jul 2021', False, False, '12 Jul 2021', False, False, '09 Jul 2021', False, False, '07 Jul 2021', False, False, '04 Jul 2021']

teams = [False, 'Utah Jazz - Los Angeles Clippers', 'Milwaukee Bucks - Phoenix Suns', False, False, 'Phoenix Suns - Milwaukee Bucks', False, False, 'Milwaukee Bucks - Phoenix Suns']

I have these two lists and I would like to make a list of tuples (date, teams) where the teams value are the teams playing (not False) and the date value is; starting from the index of the value of teams, the first value to the left that corresponds to an actual date.

I guess there is an easier way to frame to problem, but I couldn’t find it. The result should be:

date_teams = [('21 Jul 2021','Utah Jazz - Los Angeles Clippers'), ('21 Jul 2021', 'Milwaukee Bucks - Phoenix Suns'), ('15 Jul 2021', 'Milwaukee Bucks - Phoenix Suns') ... ]

Note: Can’t get rid of the False statements as they order the lists (Two matches can take place the same day)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The usual way to handle this kind of problem is to introduce an intermediate variable to hold the last valid date as you iterate through the list.

date = ['21 Jul 2021', False, False, '18 Jul 2021', False, False, '15 Jul 2021', False, False, '12 Jul 2021', False, False, '09 Jul 2021', False, False, '07 Jul 2021', False, False, '04 Jul 2021']

teams = [False, 'Utah Jazz - Los Angeles Clippers', 'Milwaukee Bucks - Phoenix Suns', False, False, 'Phoenix Suns - Milwaukee Bucks', False, False, 'Milwaukee Bucks - Phoenix Suns']

last_date = None
date_teams = []
for (d, t) in zip(date, teams):
    if d:
        last_date = d
    if t:
        date_teams.append((last_date, t))

# [('21 Jul 2021', 'Utah Jazz - Los Angeles Clippers'), ('21 Jul 2021', 'Milwaukee Bucks - Phoenix Suns'), ('18 Jul 2021', 'Phoenix Suns - Milwaukee Bucks'), ('15 Jul 2021', 'Milwaukee Bucks - Phoenix Suns')]

note that date has 19 elements while teams has only 9, and zip() will truncate the longer list in favor of the shorter list.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading