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)
CodePudding user response:
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.