python - 这个Python函数到底是做什么的?

标签 python

我无法理解这个方法的目的是什么(取自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/

相关文章:

python - Flask 中使用 Flask-Assets 的蓝图特定 Assets ?

python - Django 错误 - django.db.utils.DatabaseError : Data truncated for column 'applied' at row 1

用于搜索输入的 Python 搜索字典键

python - 在 Python 中使用可变数量的 .format() 参数进行格式化

python - Cv2 findChessboardCorners 无法找到角点

python - 在 Windows 上使用 Python 3.5 Anaconda 的 basemap

python - flask/sqlalchemy - OperationalError : (sqlite3. OperationalError) 没有这样的表

python - 在 pymongo 的 MongoClient() 中包含一个 key 文件

python - 通过 Python 中的正则表达式从列表中删除元素

python - 在 Python 中打印字符串的最有效方法?