gpt4 book ai didi

python - 向列表推导中创建的每个字典添加一个条目

转载 作者:太空宇宙 更新时间:2023-11-03 17:54:22 24 4
gpt4 key购买 nike

我使用的是 Python 2.6.6,我想这样做:

result = [ otherMethod.getDict(x).update({'foo': x.bar}) for x in someList ]  

即我有一个返回对象属性字典的方法,我在列表理解中调用该字典来构建这些字典的列表,并且我想为每个字典添加一个附加属性。但上面的语法给我留下了一个 NoneType 的列表,如下所示:

result = [ otherMethod.getDict(x) + {'foo': x.bar} for x in someList ]  

当然,我可以在列表理解之后使用循环来附加附加条目 - 但这是Python,我想在一行中完成它。我可以吗?

最佳答案

问题在于:

result = [ otherMethod.getDict(x).update({'foo': x.bar}) for x in list ]  

dict.update() 方法返回 None,因为它是一个毁坏器。考虑一下:

result = [ (d.update({'foo': x.bar}), d)[1] for d, x in ((otherMethod.getDict(x), x) for x in list) ]

如果我们不被允许使用本地函数,例如:

def update(d, e)
d.update(e)
return d

result = [ update(otherMethod.getDict(x), {'foo': x.bar}) for x in list ]

如果您不希望返回的 dict 发生变化,请考虑:

result = [ dict(otherMethod.getDict(x).values() + ({'foo': x.bar}).values()) for x in list ]  

这会根据旧字典值的串联创建一个新字典。

关于python - 向列表推导中创建的每个字典添加一个条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28689182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com