Skip to main content
 首页 » 编程设计

python之缩短长条件测试 `if find_num_3 != None and find_num_3 != i and find_num_3 != j :

2025年05月04日8luoye11

我有这样一个链条件测试:

if find_num_3 != None and find_num_3 != i and find_num_3 != j: #don't reproduce itself 

在代码中:

for i in range(len(nums)): 
    num_1= nums[i] 
    sub_target = target - num_1 
    logging.debug(f"level_1_lookup: {lookup}") 
 
    for j in range(i+1, len(nums)): 
        num_2 = nums[j] # 
        num_3 = sub_target - num_2               
        find_num_3 = lookup.get(num_3) #              
 
        if find_num_3 != None and find_num_3 != i and find_num_3 != j: #don't reproduce itself     
 
            result = [num_1, num_2, num_3] 
            triplets.append(result) 
 
            logging.debug(f"lookup: {lookup} sub_nums: {nums[j:]} \nresult: {result}") 
            logging.info(f"\ttriplets: {triplets}\n\n\n\n")                     
return triplets  

如何将长链转化为紧凑的短结构。

请您参考如下方法:

如果 find_num_3 不在 {None, i, j} 中

使用集合而不是列表或元组,因为它可以更有效地检查集合中的元素是否存在。复杂度 ~O(1) 而不是 O(n)。

集合将它们的数据存储为键/值对。键是存储对象的散列。这就是为什么你不能在一个集合中存储多个具有相同散列的对象的原因。由于散列冲突,集合中的存在性检查有时可能比 O(1) 多一点。

Here is a nice article to better understand hashes and sets.

编辑

正如@chepner 所指出的,当值仅在运行时(如问题中)已知时,使用元组比使用集合更有效,因为集合实例化比元组实例化长。