gpt4 book ai didi

python - 使用 filter() 过滤 python 字典以列出字典值

转载 作者:行者123 更新时间:2023-11-28 20:38:50 28 4
gpt4 key购买 nike

我有一个由字符串或字典组成的字典

parameters = {
"date": {'date':"2015-12-13"},
"name": "Nick",
"product": "BT Adapter",
"transaction-id": ""
}

我需要获取像 ['2015-12-13', 'BT Adapter', 'Nick'] 这样的列表

如果其中没有字典,print filter(lambda x: x if len(x) > 0 and type(x) is not dict else None, parameters.values()) 有效完美,但在它的字典中,我试图用

提取它的值
print filter(lambda x: x if len(x) > 0 and type(x) is not dict else map(lambda y: x[y], x.keys()), parameters.values())

我得到 AttributeError: 'str' object has no attribute 'keys'。如何提取所有值?

最佳答案

您误用了 filter 函数。 filter 的参数是一个谓词,它是一个返回 true/false 值的函数,filter 返回来自第二个参数的元素该函数返回 true。

例如:

print(list(filter(lambda x: 5, [1,2,3,4,5])))
[1, 2, 3, 4, 5]

因为 bool(5) == True 过滤器返回所有元素。

由于您将值 parameters.values() 作为第二个参数传递,因此无法通过仅将谓词传递给过滤器来获得预期结果。

你想要做的是这样的:

from itertools import chain

def listify(value):
if isinstance(value, dict):
return value.values()
elif value:
return [value]
return ()

print(list(chain.from_iterable(map(listify, parameters.values()))))

因此,首先将值转换为序列,然后使用 chain.from_iterable 将它们连接起来。

空值被 listify 移除,因为在这种情况下它返回一个空序列。样本运行:

In [2]: parameters = {
...: "date": {'date':"2015-12-13"},
...: "name": "Nick",
...: "product": "BT Adapter",
...: "transaction-id": ""
...: }

In [3]: print(list(chain.from_iterable(map(listify, parameters.values()))))
['2015-12-13', 'Nick', 'BT Adapter']

此外:使用嵌套条件编写复杂的 lambda 函数没有意义,因此只需使用 def 并正确编写即可。 lambda 只有在非常短的情况下才合适。

关于python - 使用 filter() 过滤 python 字典以列出字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40151291/

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