如果我将列表输入为j=1
,为什么第二个for循环(j)在迭代过程中跳过[3,3,4]
?我希望运行后answer_list为[0,1]
。
如果我将列表输入为[1,2,4]
,一切都很好。
class Solution:
def twoSum(self, nums: object, target: object) -> object:
Answer_list = []
for i in nums:
print("i_index:", nums.index(i))
for j in nums:
print("j_index:" ,nums.index(j))
if target - i - j == 0:
print (i,j)
Answer_list.append(nums.index(i))
Answer_list.append(nums.index(j))
print("Answer List:", Answer_list)
return list(set(Answer_list))
s=Solution()
print(s.twoSum([3,3,4], 6))
答案 0 :(得分:2)
问题在于nums.index(j)
将返回首次出现的索引。因此它将永远不会为[3, 3, 4].index(3)
返回1。
要使其正常运行,请遍历enumerate(nums)
,因为这还将为您提供索引:
def twoSum(self, nums: object, target: object) -> object:
Answer_list = []
for i_index, i in enumerate(nums):
print("i_index:", i_index)
for j_index, j in enumerate(nums):
print("j_index:" , j_index)
if target - i - j == 0:
print (i,j)
Answer_list.append(i_index)
Answer_list.append(j_index)
print("Answer List:", Answer_list)
return list(set(Answer_list))
您还可以通过仅在列表中进行内循环搜索 来避免一些无用的迭代。可能是这样的:
for j_index, j in enumerate(nums[i_index+1:]):
print("j_index:" , j_index+i_index+1)
if target - i - j == 0:
print (i,j)
Answer_list.append(i_index)
Answer_list.append(j_index+i_index+1)
print("Answer List:", Answer_list)