简化以下代码,算法复杂度为 O(N)
from collections import defaultdict
data = [('math', 'a'), ('math', 'a'), ('math', 'b'), ('english', 'c')]
result = defaultdict(set)
for i in data:
subject, student = i
result[subject].add(student)
print(result)
# {'math': {'a', 'b'}, 'english': {'c'}}
from collections import defaultdict
data = [('math', 'a'), ('math', 'a'), ('math', 'b'), ('english', 'c')]
result = defaultdict(set)
_ = {result[k].add(v) for k, v in data}
print(result)
# {'math': {'a', 'b'}, 'english': {'c'}}
data = [('math', 'a'), ('math', 'a'), ('math', 'b'), ('english', 'c')]
result = {key: {value for _key, value in data if _key == key} for key, _ in data}
print(result)
from itertools import groupby
from operator import itemgetter
data = [('math', 'a'), ('math', 'a'), ('math', 'b'), ('english', 'c')]
result = {k: {x[1] for x in g} for k, g in groupby(data, key=itemgetter(0))}
print(result)
# {'math': {'a', 'b'}, 'english': {'c'}}
from functools import reduce
from collections import defaultdict
data = [('math', 'a'), ('math', 'a'), ('math', 'b'), ('english', 'c')]
result = reduce(lambda d, kv: d[kv[0]].add(kv[1]) or d, data, defaultdict(set))
print(result)
# {'math': {'a', 'b'}, 'english': {'c'}}