python列表最大,在python列表中只选择最大值

I have a list of dicts as follows:

[{"server":"8.8.8.8",

"domains":[{"google.com":[{"time":15, "serial":14}, {"time":78, "serial":14}]},

{"intuit.com":[{"time":20, "serial":23}, {"time":91, "serial":18}]}

]

},

{"server":"8.8.4.4",

"domains":[{"google.com":[{"time":19, "serial":45}, {"time":92, "serial":76}]},

{"intuit.com":[{"time":45, "serial":89}, {"time":93, "serial":74}]}

]

},

{"server":"206.67.222.222",

"domains":[{"google.com":[{"time":98, "serial":76}, {"time":64, "serial":54}]},

{"intuit.com":[{"time":43, "serial":21}, {"time":65, "serial":59}]}

]

}]

How would I go about creating a structure where I select only the dict for each domain with the max serial number and when I have the same serial number, select the max time so that I am left with the following:

[{"server":"8.8.8.8",

"domains":[{"google.com":{"time":78, "serial":14}},

{"intuit.com":{"time":20, "serial":23}}

]

},

{"server":"8.8.4.4",

"domains":[{"google.com":{"time":92, "serial":76}},

{"intuit.com":{"time":45, "serial":89}}

]

},

{"server":"206.67.222.222",

"domains":[{"google.com":{"time":98, "serial":76}},

{"intuit.com":{"time":65, "serial":59}}

]

}]

解决方案

The solution using built-in max() function:

import json

# l is your initial list of dicts

for item in l:

for d in item['domains']:

for k, v in d.items():

# whether `serial` numbers are unique

has_uniq_serial = len(set([i['serial'] for i in v])) > 1

d[k] = max(v, key=lambda o: o['serial']) if has_uniq_serial else max(v, key=lambda o: o['time'])

# `json.dumps` used for pretty printing of nested dicts

print(json.dumps(l, indent=4))

The output:

[

{

"server": "8.8.8.8",

"domains": [

{

"google.com": {

"serial": 14,

"time": 78

}

},

{

"intuit.com": {

"serial": 23,

"time": 20

}

}

]

},

{

"server": "8.8.4.4",

"domains": [

{

"google.com": {

"serial": 76,

"time": 92

}

},

{

"intuit.com": {

"serial": 89,

"time": 45

}

}

]

},

{

"server": "206.67.222.222",

"domains": [

{

"google.com": {

"serial": 76,

"time": 98

}

},

{

"intuit.com": {

"serial": 59,

"time": 65

}

}

]

}

]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值