【问题标题】:Getting wrong indices for items in a list using a for loop使用 for 循环获取列表中项目的错误索引
【发布时间】:2021-09-07 19:01:53
【问题描述】:

我试图返回列表中两个元素的索引,其总和等于目标值(leetcode 问题):

def twoSum(self, nums: List[int], target: int) -> List[int]:
    for i in nums :
        for j in nums:
            if nums.index(i)!=nums.index(j) and i+j==target:
                return nums.index(i),nums.index(j)
Your input:
    [2,7,11,15]

    9

Output:
    [0,1]
Expected:
    [0,1]

对于给定的输入,上面的 sn-p 工作正常,但对于 [3,3] 它返回“[]”

Input:
    [3,3]
    6
Output:
    []
Expected:
    [0,1]

我尝试使用简单的 for 循环,而不仅仅是用于 [3,3] 的所有相同输入,它返回 [] 例如:[1,1],[2,2][1,1,1] 等等 为什么它返回 [ ]?

【问题讨论】:

    标签: list indexing


    【解决方案1】:

    问题在于 nums.index 函数的使用。它的实现方式是返回列表的第一个索引,其中参数等于列表中的元素(可以找到here)。因此,在输入为 [3, 3] 的循环的每次迭代中,nums.index(i) 和 nums.index(j) 调用始终返回 0(因为输入的第 0 个索引包含 3,即值i 和 j 的每次迭代)。因此,每次迭代的检查都失败,并且没有返回任何内容。在我重现您的问题时,我的函数返回 None 而不是 []。也许你的类型注释 None 被解释为 []。

    避免此问题的另一种方法可能包括迭代输入的索引而不是值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-13
      • 2020-09-07
      • 2018-02-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多