gpt4 book ai didi

python - For循环跳过重复索引

转载 作者:行者123 更新时间:2023-12-01 06:55:56 24 4
gpt4 key购买 nike

我刚刚学习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 时,没有任何结果。

最佳答案

index 方法返回第一次出现的索引,因此每次出现重复时您都会继续。

Python List index() The index() method searches an element in the list and returns its index. In simple terms, the index() method finds the given element in a list and returns its position. If the same element is present more than once, the method returns the index of the first occurrence of the element.

您需要重新考虑要实现的规则并采取其他措施。

如果我是你,我会迭代 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.'

关于python - For循环跳过重复索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58805697/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com