Python 列表索引未正确更新

Python 列表索引未正确更新,python,list,Python,List,在整个迭代过程中,打印列表索引得到0 class Solution(object): def twoSum(self, nums, target): indices = [] print len(nums) for i in nums: sum = 0 i_ind = nums.index(i) print ("i_ind = %d"%(i_ind))

在整个迭代过程中,打印列表索引得到0

class Solution(object):
    def twoSum(self, nums, target):
        indices = []
        print len(nums)
        for i in nums:
            sum = 0
            i_ind = nums.index(i)
            print ("i_ind = %d"%(i_ind))
            for j in nums:
                j_ind = nums.index(j)
                print ("j_ind = %d"%(j_ind))
                if i_ind != j_ind:
                    sum = i+j
                    if sum == target:
                        indices.append(i_ind)
                        indices.append(j_ind)
                        return indices
    return 0

# test case
list1  = [3,3]
target = 6
test1  = Solution()
print(test1.twoSum(list1,target))
这使得:

2
i_ind = 0
j_ind = 0
j_ind = 0
i_ind = 0
j_ind = 0
j_ind = 0
但我希望:

2
i_ind = 0
j_ind = 0
j_ind = 1

因为函数应该在找到前两个元素的和为6后终止。

如果要同时访问索引和元素,请使用
enumerate
。 说到你的问题

k = [1,1,2,2,3,3]
k.index(1)#always returns index of first occurrence. (0)
k.index(2)#always returns index of first occurrence. (2)
函数的作用是:返回列表中元素第一次出现时的索引。这会导致程序中出现意外输出。 比如说,

arr = [1, 1, 1]
print (arr.index(1))
程序总是输出0,因为这是1第一次出现的地方

您可以尝试使用enumerate()方法,该方法实际上同时迭代元素和索引

for ind, elem in enumerate(arr):
   # here ind is the index of elem in arr.
   # elem in the element you are currently at while iterating through arr 

这是来自
hackerrank
或类似网站的任务吗?您可以解释一下这段代码应该做什么(比如查找汇总到目标值的值的索引)?我投票将这个问题作为主题外的问题来结束,因为这是一个调试问题