[英]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;我有这两个列表,我想制作一个元组列表(日期,团队) ,其中团队值是正在比赛的团队(不是 False),日期值是; 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)注意:不能去掉
False
的陈述,因为他们对列表进行排序(两场比赛可以在同一天进行)
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.请注意,
date
有 19 个元素,而teams
只有 9 个, zip()
将截断较长的列表以支持较短的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.