缩短长条件测试`if find\ num\ U 3!=无并找到\u num \u 3!=我找到了第三个!=j:

2024-05-14 07:34:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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 

如何将长链转变为紧凑的短链结构。你知道吗


Tags: andnonetargetforifloggingresultfind
3条回答

如果只想减小行的大小,可以将条件括在括号中:

if (find_num_3 is not None
        and find_num_3 != i
        and find_num_3 != j):
    # ...

您可以将每个条件值存储在变量中,这很方便,因为它命名了条件并使最终条件易于理解:

defined = find_num_3 is not None
not_i = find_num_3 != i
not_j = find_num_3 != j
if defined and not_i and not_j:
    #...

或:

if all(defined, not_i, not_j):
    # ...

您还可以检查find_num_3是否在值列表中:

if find_num_3 not in (None, i, j):
    # ...

if find_num_3 not in {None, i, j}

使用set而不是list或tuple,因为检查集合中是否存在元素更有效。复杂性~O(1)而不是O(n)。你知道吗

集合将其数据存储为键/值对。密钥是存储对象的哈希。这就是为什么不能在一个集合中存储具有相同哈希的多个对象。由于哈希冲突,在一个集合中的存在性检查有时可能比O(1)多一点。你知道吗

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

编辑

正如@chepner所指出的,当值仅在运行时已知时(如问题中所述),使用tuple比使用set更有效,因为set实例化比tuple实例化长。你知道吗

替换为:

if find_num_3 not in {None, i, j}:
    #...

相关问题 更多 >

    热门问题