我目前正在使用列表理解提取一组具有某一周记录的所有用户(请参阅帖子末尾的代码)。但是,我希望获得用户以及特定周的记录。我能做的只是添加以下行:
userSubset = set([record for user in users for record in user.records if dt <= record.datetime < dt + timedelta(days=7)])
但是,这只会给我一组所有记录。我想拥有一个数据结构,每个用户都与该用户的记录相关联。也许是下面的内容(代码是为了灵感,我知道它不起作用)
userInfo = set([list(user, list(record)) for user in users for record in user.records if dt <= record.datetime < dt + timedelta(days=7)])
当前代码:
# Loop over each week in data
for dt in rrule.rrule(rrule.WEEKLY, dtstart=date_interval[0], until=date_interval[1]):
# Find users with records in interval
userSubset = set([user for user in users for record in user.records if dt <= record.datetime < dt + timedelta(days=7)])
答案 0 :(得分:1)
这样的事情怎么样?
def get_records(user, dt):
return [record for record in user.records if dt <= record.datetime < dt + timedelta(days=7)]
userInfo = [(user, get_records(user, dt)) for user in users if len(get_records(user, dt))]
每个用户调用两次get_records()函数。如果不可取,您可以先为给定的dt创建所有用户的记录列表,并在列表推导中使用该列表。
def get_all_records(users, dt):
return [[record for record in user.records if dt <= record.datetime < dt + timedelta(days=7)] for user in users]
records = get_all_records(users, dt)
userInfo = [(user, record) for user, record in zip(users, records) if len(record)]
请注意,我删除了set(),因为该对象不可清除。
所以你的最终节目看起来像这样:
from itertools import izip
def get_all_records(users, dt):
return [[record for record in user.records if dt <= record.datetime < dt + timedelta(days=7)] for user in users]
for dt in ...:
records = get_all_records(users, dt)
userInfo = [(user, record) for user, record in izip(users, records) if len(record)]