关于python数据处理的问题

host_msg = [
{'ipv4': ['10.0.0.1'], '10.0.0.1': [{'switch': '00:00:00:00:00:00:00:01', 'port': '4'}]}, 
{'ipv4': ['10.0.0.3'], '10.0.0.3': [{'switch': '00:00:00:00:00:00:00:0a', 'port': '4'}]}, 
{'ipv4': ['10.0.0.2'], '10.0.0.2': [{'switch': '00:00:00:00:00:00:00:0b', 'port': '4'}]}
]

我希望host_msg按照ipv4的大小进行排序,变成下面这中输出

host_msg = [
{'ipv4': ['10.0.0.1'], '10.0.0.1': [{'switch': '00:00:00:00:00:00:00:01', 'port': '4'}]}, 
{'ipv4': ['10.0.0.3'], '10.0.0.3': [{'switch': '00:00:00:00:00:00:00:0a', 'port': '4'}]}, 
{'ipv4': ['10.0.0.2'], '10.0.0.2': [{'switch': '00:00:00:00:00:00:00:0b', 'port': '4'}]}
]

请问各位应该怎么做?

Jason990420
最佳答案

sorted(iterable, /, *, key=None, reverse=False)

Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order.

>>> new_host_msg = sorted(host_msg, key=lambda x:x['ipv4'][0])
>>> new_host_msg
[{'10.0.0.1': [{'port': '4', 'switch': '00:00:00:00:00:00:00:01'}], 'ipv4': ['10.0.0.1']},
 {'10.0.0.2': [{'port': '4', 'switch': '00:00:00:00:00:00:00:0b'}], 'ipv4': ['10.0.0.2']},
 {'10.0.0.3': [{'port': '4', 'switch': '00:00:00:00:00:00:00:0a'}], 'ipv4': ['10.0.0.3']}]
1周前 评论
讨论数量: 1
Jason990420

sorted(iterable, /, *, key=None, reverse=False)

Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order.

>>> new_host_msg = sorted(host_msg, key=lambda x:x['ipv4'][0])
>>> new_host_msg
[{'10.0.0.1': [{'port': '4', 'switch': '00:00:00:00:00:00:00:01'}], 'ipv4': ['10.0.0.1']},
 {'10.0.0.2': [{'port': '4', 'switch': '00:00:00:00:00:00:00:0b'}], 'ipv4': ['10.0.0.2']},
 {'10.0.0.3': [{'port': '4', 'switch': '00:00:00:00:00:00:00:0a'}], 'ipv4': ['10.0.0.3']}]
1周前 评论

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!