我的python很差,在此代码中找不到错误

时间:2018-12-07 03:20:52

标签: python python-3.x

为什么此代码会空列表?我无法理解。

class Solution:
    def twoSum(self, nums, target):
        results = []
        for i in nums:
            for j in nums:
                if i + j == target and nums.index(i) != nums.index(j):
                    a = nums.index(i)
                    results.append(a)
                    b = nums.index(j)
                    results.append(b)
        return results

h = Solution()
result = h.twoSum([3, 3], 6)
print(result)

结果是一个空列表。

1 个答案:

答案 0 :(得分:0)

您的问题让我记住了初学者。快到那儿,试试这个哥们

    class Solution:

    def twoSum(self,nums, target): 
        results = [] 
        for i,val1 in enumerate(nums): 
            for j,val2 in enumerate(nums): 
                if val1+val2 == target and i != j: 
                   results.append([i,j]) 
        return results
    h = Solution()
    result = h.twoSum([3, 3, 2, 4], 6)
    print result

    Result:[[0, 1], [1, 0], [2, 3], [3, 2]]

如果条件nums.index(i)!= nums.index(j)不起作用,请尝试枚举以建立索引