【问题标题】:why is my for loop within a for loop causing issues?为什么我的 for 循环中的 for 循环会导致问题?
【发布时间】:2021-04-14 10:54:04
【问题描述】:

我有以下代码,其中我们有两个唯一整数列表,nums1 和 nums2;其中 nums1 是 nums2 的子集。我们想将 nums1 的每个元素与 nums2 进行比较,并将 'output_stack' 附加到 nums2 中的下一个最大整数。

例如: 输入:nums1 = [4,1,2], nums2 = [1,3,4,2] 输出:[-1,3,-1] 解释: 对于第一个数组中的数字 4,您在第二个数组中找不到下一个更大的数字,因此输出 -1。 对于第一个数组中的数字 1,第二个数组中的下一个更大的数字是 3。 对于第一个数组中的数字 2,第二个数组中没有下一个更大的数字,因此输出 -1。

def nextGreaterElement(nums1, nums2):
    nums1 = sorted(nums1)
    nums2 = sorted(nums2)


    output_stack = []
    for i in range(len(nums1)):
        for j in range(len(nums2)):
            if nums1[i] ==nums2[-1]:
                output_stack.append(-1)

            elif nums1[i] == max(nums2):
                output_stack.append(-1)

            elif nums1[i] == nums2[j]:
                output_stack.append(nums2[j+1])

            else:
                output_stack.append(-1)

        return(print(output_stack))

nextGreaterElement([2,4],[1,2,3,4])

上面的代码返回了错误的输出 [-1,3,-1,-1],我知道为什么——这是因为我用 j 遍历了所有 nums2,但这是我知道的唯一方法做。有没有办法修改现有的代码。

我的麻烦是,如果我去掉第二个“for”循环,我很难找到一种方法来引用 nums2 中的“下一个”索引;有没有办法在不使用“for”循环的情况下做到这一点?

【问题讨论】:

    标签: python loops


    【解决方案1】:

    尝试退出 else-if 结构中的第二个 for 循环:

        for i in range(len(nums1)):
          for j in range(len(nums2)):
            if nums1[i] ==nums2[-1]:
                output_stack.append(-1)
                break
            elif nums1[i] == max(nums2):
                output_stack.append(-1)
                break
            elif nums1[i] == nums2[j]:
                output_stack.append(nums2[j+1])
                break
            else:
                output_stack.append(-1)
                break
        return(print(output_stack))
    

    【讨论】:

    • 但这意味着代码只计算 nums1 的第一个元素,对吧?但我希望它评估所有元素。
    • 我得到了答案:我做到了 if len(output_stack) == len(nums1): break
    【解决方案2】:

    我不确定您的代码为什么不起作用,但我想我会尝试制作自己的版本。可以清理一下,但似乎适用于您的两个示例

    def nextGreaterElement(nums1, nums2):
        results = []
        for i in range(len(nums1)):
            greater_numbers = nums2[i:][np.where(nums2[i:] > nums1[i])]
            if len(greater_numbers) > 0:
                results += [greater_numbers[0]]
            else:
                results += [-1]
        return np.array(results)
            
    
    list1 = np.array([4, 1, 2])
    list2 = np.array([1, 3, 4, 2])
    
    nextGreater = nextGreaterElement(list1, list2)
    print(nextGreater)
    

    下面是代码的工作原理:

    首先,我们需要遍历第一个列表中的数字:

    for i in range(len(nums1)):
    

    然后,我们希望在与第一个点相同的索引处对第二个列表进行切片。我将使用 nums1 作为 [4, 1, 2] 和 nums2 作为 [1, 3, 4, 2] 来做这个示例,查看 nums1 中的 '1'。

    nums2[i:]
    
    (value 1 is at index 1, nums2[1:] returns array([3, 4, 2]))
    

    找到切片列表中大于我们正在查看的数字的数字的位置

    np.where(nums2[i:] > nums1[i])
    
    (at i=1, this returns the index positions (array([0, 1, 2], dtype=int64),) as all of the numbers in [3,4,2] are greater than 1)
    

    然后索引切片nums2列表以返回实际值

    greater_numbers = nums2[i:][np.where(nums2[i:] > nums1[i])]
    
    returns array([3, 4, 2])
    

    在获取列表中的第一个数字之前,我们需要检查数组中是否包含任何值

    if len(greater_numbers) > 0:
        results += [greater_numbers[0]]
    else:
        results += [-1]
    

    将结果作为 numpy 数组返回以保持一致性。我最初将结果附加到列表中,因为它们是可变的。我不确定最好的做法是什么,但我就是这样做的!

    return np.array(results)
    

    【讨论】:

    • 嗨,汤姆,谢谢。快速提问, Greater_numbers = nums2[i:][np.where(nums2[i+1:] > nums1[i])] 行是做什么的?我知道 np 是 Numpy 以及它是如何工作的,但是在其他代码中我迷失了它究竟做了什么。谢谢
    • @odablocker 嗨,我已经编辑了我的答案,解释了一些代码是如何工作的。该行实际上有一个错误。在您的回答中,您说结果应该是 [-1,3,-1] 但我认为您的意思是 [-1 3 4] 或 [-1 4 -1]。如果是第二个版本,将greater_numbers赋值代码替换为:greater_numbers = nums2[i+1:][np.where(nums2[i+1:] > nums1[i])]
    猜你喜欢
    • 1970-01-01
    • 2011-04-23
    • 2018-10-11
    • 2016-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    相关资源
    最近更新 更多