Reputation: 1949
I have two dicts that track the type of transportation I use over a weekly period:
transportation = {
'car':[1,0,0,0,0,0,1],
'walk':[0,1,0,1,0,0,0],
'bike':[0,1,1,0,1,0,0],
}
grains = {
'overall':['car','walk','bike'],
'environmentally_friendly':['walk','bike'],
}
I would like to rollup the data to calculate when I was using transportation over the past week:
using_transportation = {
'overall': 6,
'environmentally_friendly': 4,
}
If the week is Sunday through Saturday, overall
is 6 because I do not use transportation on Friday. environmentally_friendly
is 4 because Monday I walk and bike (only counts as 1), and then either walk or bike Tues - Thurs.
This is what I'm using for calculating overall, but not sure how to break out for environmentally_friendly (can't use pandas unfortunately):
week = []
day = []
i = 0
while i <= 6:
for k,v in datelist.items():
day.append(v[i])
if 1 in day:
week.append(True)
else:
week.append(False)
day = []
i+=1
print(sum(week))
Any advice on a better way is much appreciated!
Upvotes: 0
Views: 70
Reputation: 2227
Here is a way you could solve the problem:
transportation = {
'car':[1,0,0,0,0,0,1],
'walk':[0,1,0,1,0,0,0],
'bike':[0,1,1,0,1,0,0],
}
grains = {
'overall':['car','walk','bike'],
'environmentally_friendly':['walk','bike'],
}
def save_the_planet(transportation, grains):
# Let't do the week plan (as a bonus)
def go(x, i): return [k for (k, v) in x.items() if v[i] == 1]
week = {
'monday': go(transportation, 0),
'tuesday': go(transportation, 1),
'wednesday': go(transportation, 2),
'thursday': go(transportation, 3),
'friday': go(transportation, 4),
'saturday': go(transportation, 5),
'sunday': go(transportation, 6),
}
# Now lets calculate
overall = transportation.keys()
not_eco = [x for x in overall if x not in grains['environmentally_friendly']]
not_eco = {k:v for k,v in week.items() if any([x in v for x in not_eco])}
eco_week = {k:v for k,v in week.items() if k not in not_eco.keys()}
# Then le'ts reveal the answer
return {
'overall': len([x for x in week.values() if x]),
'environmentally_friendly': len([x for x in eco_week.values() if x]),
}
print(save_the_planet(transportation, grains))
You can probably optimize it a bit
Upvotes: 1