Python结构化列表不使用带Lambda的Reduce返回值



我继承了Python代码,但我还不完全理解。这里是一个结构化列表,它只需要函数返回Alternatives键的值。数据类似

{
'Response': 
[
{
'SavingsMessage': '', 
'SavingNotification': 
[
{'AuthorizationNumber': '12345' 'Alternatives': []},
{'AuthorizationNumber': '6666', 'Alternatives': [{'NDC': '99999'} ]
]
}

上述数据在nested_value变量中,并以以下格式传递给函数:

level_two = get_nested_value_IRFAN([nested_value,*schema[key][level_one_key][level_one_key]])

而CCD_ 3的值为:

[0, 'Response', 0, 'SavingNotification', 0, 'Alternatives']

这里是函数本身:

def get_nested_value_IRFAN(path):   
return functools.reduce(lambda a,b:a[b],path)

根据我对代码的理解,函数应该只返回Alternatives键的值,但函数什么都不返回——只返回空白的[]?或者,我可以以不同的方式使用nested_value变量来提取Alternative键的值。我尝试了一些方法,但到目前为止都没有效果。

提前感谢!

使用reduce的方法很好,但您的代码和/或数据存在一些问题:

  • 首先,您的nested_value结构不正确;缺少几个闭合的parens和一个逗号(可能还有整个外层(
  • 您可以使用reduce:initializer的第三个参数,而不是将实际数据链接到路径
  • 路径中的第一个关键字是0,但在nested_value中,最外层的结构是字典

或者应该有另一个列表吗?如果存在另一个列表,那么[]实际上将是给定路径和数据的正确响应。无论如何,我建议至少使用initializer参数来使代码更加清晰:

nested_value = [{'Response': [{'SavingsMessage': '',
'SavingNotification': [{'AuthorizationNumber': '12345',
'Alternatives': []},
{'AuthorizationNumber': '6666', 'Alternatives': [{'NDC': '99999'}]}]}]}]
def get_nested_value_IRFAN(path, data): 
return functools.reduce(lambda a, b: a[b], path, data)
# using 1 instead of 0 as last list index for clearer output
path = [0, 'Response', 0, 'SavingNotification', 1, 'Alternatives']
val = get_nested_value_IRFAN(path, nested_value)
# [{'NDC': '99999'}], or [] for original path

由于评论的空间和格式有限,我发布了一个答案。

你给我们的:

nested_value = {
'Response': 
[
{
'SavingsMessage': '', 
'SavingNotification': 
[
{'AuthorizationNumber': '12345' 'Alternatives': []},
{'AuthorizationNumber': '6666', 'Alternatives': [{'NDC': '99999'} ]
]
}
path = [0, 'Response', 0, 'SavingNotification', 0, 'Alternatives']
def get_nested_value_IRFAN(path):
return functools.reduce(lambda a,b:a[b],path)
get_nested_value_IRFAN([nest_value, path])

functools.reduce()需要一个函数和一个数据集进行迭代。传入的函数将上一次迭代的结果存储在a中,并获得要在b中使用的新值。在第一次迭代中,它接收列表的前两个元素(在我们的例子中为path(。

因此,在应用函数时,迭代看起来像:

a = the nested_value data structure wrapped in [], b = 0
a = the nested_value data structed, b = "Response"
a = nested_value["Response"], b = 0
a = nested_value["Response"][0], b = "SavingNotification"
a = nested_value["Response"][0]["SavingNotification"], b = 0
# below is the last iteration
a = nested_value["Response"][0]["SavingNotification"][0], b = "Alternatives"
# which returns nested_value["Response"][0]["SavingNotification"][0]["Alternatives"]
# which is also []

您可以创建一个循环,以最小的工作量获得其他值,如:

dkey = schema[key][level_one_key][level_one_key]
level_two = get_nested_value_IRFAN([nested_value,*dkey[:-2]])
for e in level_two:
# Okay... so this one should work... but if it doesn't, then you can do...
print(e[dkey[-1]])
print(e["Alternatives"]
# do what you want with e

最新更新