我有一个嵌套列表,可以在其中接收数据,但是该列表可以更改。如果列表更改,如何获取一些值?
alltext=[{
"name": "sample string 1",
"relationships": [
{
"isBlocked": False,
"orderIndex": 1,
"relationship": {
"debts": [
{
"currency": {
"id": "sample string2",
"isoCode": "string",
"isoNumber3": "string",
"name": "string"
},
#"sum"#: 0.0
}
],
"deferment": 90,
"id": "string",
#"name"#: "string 1",
"overdueDebts": [
{
"currency": {
"id": "string",
"isoCode": "string",
"isoNumber3": "string",
"name": "string"
},
#"sum"#: 1000.0
}
],
"vendorId": "string"
}
},
{
"isBlocked": False,
"orderIndex": 2,
"relationship": {
"debts": [
{
"currency": {
"id": "string",
"isoCode": "string",
"isoNumber3": "string",
"name": "string"
},
#"sum"#: 0.0
}
],
"deferment": 90,
"id": "string",
"limit": 0.0,
#"name"#: "string ",
"overdueDebts": [
{
"currency": {
"id": "string",
"isoCode": "string",
"isoNumber3": "string",
"name": "string"
},
#"sum"#: 2000.0
}
],
"vendorId": "string"
}
}
]
}
]
我试图以它为例
for i in range(len(alltext)):
ordersname.append(alltext[i]['relationships'][0]['relationship']['name'])
或喜欢它:
Debts.append([routeDict['sum'] for routeDict in alltext[i]['relationships'][0]['relationship']['debts']])
OverdueDebts.append([routeDict['sum'] for routeDict in alltext[i]['relationships'][0]['relationship']['overdueDebts']])
我了解到,我之所以这么认为,是因为我和[0]
始终是第一位的。如果O删除[0]
我收到错误TypeError: list indices must be integers or slices, not str
我想从所有关系中的债务和逾期债务和名称中获取总和(我标记了我想要拥有的所有东西
答案 0 :(得分:3)
我将其标记为映射减少问题。 Map-reduce是许多可用解决方案中的常见问题。我鼓励您看一些例子。将来,请发布您尝试过的内容。
这里是映射减少词典的一种方法。我实例化一个新的空数组,遍历每个关系,然后向该数组添加新的字典。
array_of_dicts = []
for relationship in main_dict['relationships']:
r = relationship['relationship']
debts = sum([debt['sum'] for debt in r['debts']])
overdue = sum([debt['sum'] for debt in r['overdueDebts']])
array_of_dicts.append({
'name': r['name'],
'debt': debts,
'overdue': overdue
})
Python提供了许多用于map-reduce的快捷方式,例如lambda函数和内置函数。我正在使用一些列表理解,但可以很容易地使用字典理解。
答案 1 :(得分:1)
让我添加一些功能性方法(因为我们想学习多种策略来解决此问题)
import toolz.curried
from operator import itemgetter
get_name = toolz.curried.get_in(['relationship', 'name'])
get_debts = toolz.curried.get_in(['relationship', 'debts'])
get_overdue = toolz.curried.get_in(['relationship', 'overdueDebts'])
debt_sum = toolz.compose_left(get_debts, toolz.curried.map(itemgetter('sum')), sum)
overdue_sum = toolz.compose_left(get_overdue, toolz.curried.map(itemgetter('sum')), sum)
collect_info = toolz.juxt(get_name, debt_sum, overdue_sum)
list(map(collect_info, blubb['relationships']))
需要阅读代码的可怜的灵魂;-) ... 因此,@ solbs的答案比这更具可读性。