用字典列表中的前缀“ ble_mac_”替换为“ ble_mac”的最佳列表理解方法是什么?
Given List : [{'ble_mac_2': 'DCE83F3BC820', 'location': '818'},
{'ble_mac_2': 'DCDC9FD25476', 'location': '819'},
{'ble_mac_3': 'DCDC9FD25473', 'location': '819'},
{'ble_mac_4': 'DCDC9FD25474', 'location': '819'}]
Expected List : [{'ble_mac': 'DCE83F3BC820', 'location': '818'},
{'ble_mac': 'DCDC9FD25476', 'location': '819'},
{'ble_mac': 'DCDC9FD25473', 'location': '819'},
{'ble_mac': 'DCDC9FD25474', 'location': '819'}]
答案 0 :(得分:4)
您可以结合使用list和dict理解,并通过正则表达式应用替换:
import re
lst = [{ re.sub("^ble_mac_.*", "ble_mac", k): v for k, v in d.items()} for d in lst]
没有正则表达式,它可能会运行得更快一些:
lst = [{ "ble_mac" if k.startswith("ble_mac_") else k: v for k, v in d.items()} for d in lst]
答案 1 :(得分:1)
通过使用嵌套的list
和dictionary
理解。
Extected_List = [{'ble_mac' if 'ble_mac' in k[0:7] else k:v for k,v in i.items()} for i in Given_List]
Expected_List
[{'ble_mac': 'DCE83F3BC820', 'location': '818'},
{'ble_mac': 'DCDC9FD25476', 'location': '819'},
{'ble_mac': 'DCDC9FD25473', 'location': '819'},
{'ble_mac': 'DCDC9FD25474', 'location': '819'}]