我无法理解这个方法的目的是什么(取自Python Brain Teaser 问题库)。我发现输入似乎是字典的集合。但是,这个方法想要做什么?
def g(items):
d = defaultdict(list)
for i in items:
d[i['type']].append(i)
return d
最佳答案
它获取一堆可按字符串索引的项目,并按 "type"
键处的值对它们进行分组。结果是一个字典,其中键是“type”
的值,并且该值是具有所述键作为其“type”
的所有项目的列表。
它似乎确实有点损坏,因为它正在返回该函数。我认为预期的行为是最后有 return d
。通过以下实现:
def g(items):
d = defaultdict(list)
for i in items:
d[i['type']].append(i)
return d # Fixed this
您提供以下输入:
items = [
{'type': 'foo', 'val': 1},
{'type': 'bar', 'val': 2},
{'type': 'foo', 'val': 3}
]
您将得到以下输出:
{'foo': [{'type': 'foo', 'val': 1}, {'type': 'foo', 'val': 3}], 'bar': [{'type': 'bar', 'val': 2}]}
关于python - 这个Python函数到底是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33949482/