59 lines
1.5 KiB
Python
59 lines
1.5 KiB
Python
from functools import reduce
|
|
import collections
|
|
from pprint import pprint
|
|
import itertools
|
|
|
|
Scientist = collections.namedtuple('Scientist', [
|
|
'name',
|
|
'field',
|
|
'born',
|
|
'nobel',
|
|
])
|
|
|
|
scientists = (
|
|
Scientist(name='Ada Lovelace', field='math', born=1815, nobel=False),
|
|
Scientist(name='Emmy Noether', field='math', born=1882, nobel=False),
|
|
Scientist(name='Marie Curie', field='physics', born=1867, nobel=True),
|
|
Scientist(name='Tu Youyou', field='chemistry', born=1930, nobel=True),
|
|
Scientist(name='Ada Yonath', field='chemistry', born=1939, nobel=True),
|
|
Scientist(name='Vera Rubin', field='astronomy', born=1928, nobel=False),
|
|
Scientist(name='Sally Ride', field='physics', born=1951, nobel=True),
|
|
)
|
|
|
|
names_and_agesLC = tuple({'name': x.name, 'age': 2021 - x.born}
|
|
for x in scientists)
|
|
#pprint(names_and_agesLC)
|
|
|
|
total_age = reduce(
|
|
lambda acc,val: acc + val['age'],
|
|
names_and_agesLC,
|
|
0)
|
|
#pprint(total_age)
|
|
|
|
total_age = sum(x['age'] for x in names_and_agesLC)
|
|
#print(total_age)
|
|
|
|
def reducer(acc, val):
|
|
acc[val.field].append(val.name)
|
|
return acc
|
|
|
|
scientists_by_field = reduce(
|
|
reducer,
|
|
scientists,
|
|
{'math':[], 'physics':[], 'chemistry':[], 'astronomy':[]}
|
|
)
|
|
#pprint(scientists_by_field)
|
|
|
|
scientists_by_field = reduce(
|
|
reducer,
|
|
scientists,
|
|
collections.defaultdict(list)
|
|
)
|
|
#pprint(scientists_by_field)
|
|
|
|
scientists_by_field = {
|
|
item[0]:list(item[1])
|
|
for item in itertools.groupby(scientists, lambda x: x.field)
|
|
}
|
|
pprint(scientists_by_field)
|