Python 用于跳过重复索引的循环
我正在学习Python,我正在尝试制作一个小程序,用户可以在其中输入一个数字列表,然后输入一个目标数字。然后,程序将循环添加列出的每个数字,以查看是否有任何数字可以添加到该目标数字并返回索引。然而,如果用户输入了一个重复的数字,它会完全跳过该索引,所以我不知道它为什么这样做,或者如何修复它Python 用于跳过重复索引的循环,python,python-3.x,Python,Python 3.x,我正在学习Python,我正在尝试制作一个小程序,用户可以在其中输入一个数字列表,然后输入一个目标数字。然后,程序将循环添加列出的每个数字,以查看是否有任何数字可以添加到该目标数字并返回索引。然而,如果用户输入了一个重复的数字,它会完全跳过该索引,所以我不知道它为什么这样做,或者如何修复它 elements = input('Please enter your elements: ') given = list(map(int,elements.split(','))) print(given)
elements = input('Please enter your elements: ')
given = list(map(int,elements.split(',')))
print(given)
target = int(input('Please enter your target number: '))
def get_indices_from_sum(target):
for x in given:
for y in given:
if given.index(x) == given.index(y):
continue
target_result = x + y
if target_result == target:
result = [given.index(x), given.index(y)]
print('Success!')
return result
else:
continue
if target_result != target:
return 'Target cannot be found using elements in the given list.'
print(get_indices_from_sum(target))
例如,如果有人输入了一个2,7,10,14的列表,目标数字为9,则返回[0,1]。另一方面,当我尝试一个2,3,3,10的列表和一个6的目标时,什么也没有返回。index方法返回第一次出现的索引,因此每次出现重复时,您都会继续 Python List index()index()方法搜索列表中的元素并返回其索引。简单来说,index()方法在列表中查找给定元素并返回其位置。如果同一元素多次出现,则该方法返回该元素第一次出现的索引 你需要重新思考你想要实施的规则,并采取其他措施 如果我是你,我会迭代
枚举(给定)
而不是迭代给定
,这样你就可以正确地比较索引
for idx, x in enumerate(given):
for idy, y in enumerate(given):
if idx == idy:
continue
target_result = x + y
if target_result == target:
result = [idx, idy]
print('Success!')
return result
else:
continue
if target_result != target:
return 'Target cannot be found using elements in the given list.'
啊,我明白了。你能解释一下“for idx,x”部分吗?我不知道我明白那是怎么回事。它基本上是说“对于位置idx,值x”
枚举(给定)
将返回一个包含两个对象的元组,即数组的当前索引和该索引的当前值。这里这个元组只是被解压成两个命名变量。因此,idx
将指向索引的当前值,x
将指向索引的当前值。基本上,对于枚举,我需要在for循环中声明2个变量。谢谢你的帮助!是的,第一个跟踪索引,第二个跟踪值而不是列表,您可以将给定的值输入到只包含唯一数字的集合中。