[英]Is there a better way to compare two lists in Python, stopping at the shorter list?
[英]Python: Better way to compare two elements within two nested dict / list
有没有更好的方法来比较两个嵌套的字典/列表而不使用嵌套的 for 循环。 我正在尝试匹配来自两个不同来源的设备的序列号,并创建一个字典 output 来组合两个数据。 有两个 for 循环对我有用,但我觉得有更好的方法来做到这一点。 实际上,list_one 有 15000 条记录,list_two 有 8000 条记录。 我很确定,list_one 中的每条记录都在遍历 list_two 中的 8000 条记录以找到匹配项,所以基本上,它使用 if 语句检查 120,000,000 种可能性。
list_one = [{'sn': '1234', 'model': 'Dell', 'last_checkin': '8/22/2022'}, {'sn': '2234', 'model': 'Dell', 'last_checkin': '8/22/2022'}, {'sn': '3234', 'model': 'Dell', 'last_checkin': '8/22/2022'}]
list_two = [['1234', 'user_a', '8/22/2022'], ['2234', 'user_b', '8/22/2022'], ['3234', 'user_c', '8/22/2022']]
result_list = []
for l in list_one:
for t in list_two:
if l['sn'] == t[0]:
result = {'sn': l['sn'], 'user': t[1], 'check_in': l['last_checkin']}
result_list.append(result)
你可以尝试这样的事情:
list_one = [{'sn': '1234', 'model': 'Dell', 'last_checkin': '8/22/2022'}, {'sn': '2234', 'model': 'Dell', 'last_checkin': '8/22/2022'}, {'sn': '3234', 'model': 'Dell', 'last_checkin': '8/22/2022'}]
list_two = [['1234', 'user_a', '8/22/2022'], ['2234', 'user_b', '8/22/2022'], ['3234', 'user_c', '8/22/2022']]
lam = lambda l1: None if len(x:= [{"sn": l1["sn"], "user": l2[1], "check_in": l1["last_checkin"]} for l2 in list_two if l2[0] == l1['sn']]) == 0 else x
result_list = map(lam, list_one)
print(*result_list)
我不知道这是否适合您,但您可以尝试类似的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.