我已经扫描了蓝牙设备列表,看起来像:-
[{'address': '00:0C:99:88:77:66', 'name': 'FK20020', 'rssi': -49, 'packet_data': {'connectable_advertisement_packet': {'flags': bytearray(b'\x06'), 'complete_list_16-bit_service_class_uuids': bytearray(b'\t\x18\x02\x18'), 'complete_local_name': 'FK20020'}, 'scan_response_packet': {}}}, {'address': '77:11:22:33:44:55', 'name': 'PQR11225', 'rssi': -49, 'packet_data': {'connectable_advertisement_packet': {'flags': bytearray(b'\x06'), 'incomplete_list_128-bit_service_class_uuids': bytearray(b'\x07\xb9\xf9\xd7P\xa4 \x89w@\xcb\xfd,\xc1\x80H'), 'complete_local_name': 'PQR11225'}, 'scan_response_packet': {}}}, {'address': '77:55:33:22:44:99', 'name': 'PQR05286', 'rssi': -49, 'packet_data': {'connectable_advertisement_packet': {'flags': bytearray(b'\x06'), 'incomplete_list_128-bit_service_class_uuids': bytearray(b'\x08\xc9\xf9\xd9P\xa4 \x89w@\xcb\xdd,\xc3\x90H'), 'complete_local_name': 'PQR05286'}, 'scan_response_packet': {}}}]
从列表中,我只希望名称以“ PQR”开头的设备(例如PQR11225或PQR05286),并形成一个包含其“名称”,“地址”和“ rssi”的列表。
有没有办法做到这一点?
答案 0 :(得分:2)
您可以循环浏览列表,仅选择以PQR
开头的名称
result = []
for device in devices:
if device['name'].startswith('PQR'):
result.append(device)`
答案 1 :(得分:1)
列表补偿方法-
[(i['name'], i['address'], i['rssi']) for i in bluetooth_list if i['name'].startswith('PQR')]
答案 2 :(得分:1)
如果您想使用列表组件:
got=[(i['name'],i['address'],i['rssi']) for i in devices if i['name'].startswith('PQR')]
答案 3 :(得分:1)
为此,您可以使用filter
作为
res = []
for dev in list_:
if dev['name'].startswith('PQR'):
tmp = {'name':dev['name'],'address':dev['address'], 'rssi':dev['rssi']}
res.append(tmp)
print(res)
输出
[{'name': 'PQR11225', 'address': '77:11:22:33:44:55', 'rssi': -49}, {'name': 'PQR05286', 'address': '77:55:33:22:44:99', 'rssi': -49}]
答案 4 :(得分:1)
您可以根据设备名称过滤列表:
list(filter(lambda s: s['name'].startswith('PQR'), my_list))
输出:
[{'address': '77:11:22:33:44:55',
'name': 'PQR11225',
'rssi': -49,
'packet_data': {'connectable_advertisement_packet': {'flags': bytearray(b'\x06'),
'incomplete_list_128-bit_service_class_uuids': bytearray(b'\x07\xb9\xf9\xd7P\xa4 \x89w@\xcb\xfd,\xc1\x80H'),
'complete_local_name': 'PQR11225'},
'scan_response_packet': {}}},
{'address': '77:55:33:22:44:99',
'name': 'PQR05286',
'rssi': -49,
'packet_data': {'connectable_advertisement_packet': {'flags': bytearray(b'\x06'),
'incomplete_list_128-bit_service_class_uuids': bytearray(b'\x08\xc9\xf9\xd9P\xa4 \x89w@\xcb\xdd,\xc3\x90H'),
'complete_local_name': 'PQR05286'},
'scan_response_packet': {}}}]