Python 二和LeetCode-我自己的代码失败的原因

Python 二和LeetCode-我自己的代码失败的原因,python,python-3.x,Python,Python 3.x,问题: 给定一个整数数组,返回两个数字的索引,使它们相加到一个特定的目标。您可以假设每个输入都有一个解决方案,并且不能两次使用同一个元素 我的代码: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for x in nums: for y in nums: i

问题:

给定一个整数数组,返回两个数字的索引,使它们相加到一个特定的目标。您可以假设每个输入都有一个解决方案,并且不能两次使用同一个元素


我的代码:

def twoSum(self, nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: List[int]
    """
    for x in nums:
        for y in nums: 
            if nums.index(x) != nums.index(y) and x + y == target :
                    return [nums.index(x), nums.index(y)]

 print (twoSum ([3, 3],6))
输出:

null
在我看来,第一次“迭代”(我不确定这是否是正确的术语)看起来像:

If 0 != 0 (False) and 3 + 3= 6 (True)  --> as  the first condition is not met, the y loops
因此,下一次迭代如下所示:

If 0 != 1 (True) and 3 + 3 = 6 (True) 
-->由于满足上述条件,函数将返回
[0,1]
,但实际上代码返回
null
,我不理解原因


因此,如果有人能解释发生了什么,或者告诉我一些关键字,以便我自己搜索答案,我将不胜感激:)

index方法将找到列表中第一次出现的索引。由于列表中有两个相同的数字,因此在编写的代码中调用
index
将不会返回除0以外的任何结果。因此,如果nums.index(x)!=nums.index(y)从来都不是
True
,因此函数返回
None

正如MoxieBall指出的,代码返回
None
,因为
.index()
返回第一个匹配值的索引

您可以使用
enumerate()
获取真正的索引位置:

for x_index, x_value in enumerate(nums):
    for y_index, y_value in enumerate(nums):
        if x_index != y_index and x_value + y_value == target:
            return [x_index, y_index]

我认为,由于[3,3]中的两个元素是相同的,因此nums.index(x)和nums.index(y)总是给出等于0的值,因此if块永远不会执行

def twoSum(self, nums, target):
  for x in range(len(nums)):
    for y in range(len(nums)): 
        if x != y and nums[x] + nums[y] == target :
                return [x, y]
print (twoSum ([3, 3],6))
这是我的解决方案