For循环跳过重复索引

时间:2019-11-11 17:02:55

标签: python python-3.x

我正在学习Python,并且正在尝试制作一个小程序,用户可以在其中输入数字列表,然后输入目标数字。然后,程序将执行循环以添加列出的每个数字,以查看是否有任何数字可以添加到该目标数字并返回索引。但是,如果用户输入重复的数字,则会完全跳过该索引,因此我不确定为什么这样做或如何解决。

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的目标时,什么也没回来。

1 个答案:

答案 0 :(得分:1)

索引方法返回第一个出现的索引,因此,每次有重复项时,您都将继续操作。

  

Python列表index()index()方法搜索列表中的元素并返回其索引。简单来说,index()方法在列表中找到给定的元素并返回其位置。如果同一元素多次出现,则该方法返回该元素首次出现的索引。

您需要重新考虑要实施的规则,然后再进行其他修改。

如果我是我,我将遍历enumerate(given)而不是遍历given,这样您就可以正确比较索引。

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.'