如何在不包含相同元素两次的情况下遍历列表?

How to iterate through a list without including the same element twice?

我想知道如何在不包含相同数字两次的情况下遍历此列表。

import itertools

def sum_pairs(ints, s):
    indexes = []
    pair = []
    for numbers in itertools.combinations(ints,2):
        if sum(numbers) == s:
            pair.append(numbers)
            for n in numbers:
                indexes.append(ints.index(n))
    print(pair)
    print(indexes)

a = [10, 5, 2, 3, 7, 5]
target = 10

这是输出:

[(5, 5), (3, 7)]
[1, 1, 3, 4]

'pair' 正确输出 5 和 5 等于 10,但是当我使用变量 'indexes' 检查数字的来源时,我可以看到相同的 5 被使用了两次,第二次五个从未被考虑过。我正在寻找的是,如果它在同一索引中,我如何修改它以不添加相同的数字两次。对于前。索引的输出将是 [1, 5, 3, 4].

非常感谢。

运行 索引上的组合代替。顺便说一句,您的索引定义不太常见。如果您明白我的意思,请尝试在

下方添加一个附加项来更改 'extend'
def sum_pairs(ints, s):
    indexes = []
    pair = []
    for numbers in itertools.combinations(range(len(ints)),2):
        if ints[numbers[0]]+ints[numbers[1]] == s:
            indexes.extend(numbers)
            pair.append((ints[numbers[0]],ints[numbers[1]]))
    print(pair)
    print(indexes)

使用 enumerate:

走私每个值的索引
import itertools

def sum_pairs(ints, s):
    indexes = []
    pair = []
    for (ix, x), (iy, y) in itertools.combinations(enumerate(ints),2):
        if x + y == s:
            pair.append((x, y))
            indexes += (ix, iy)
    print(pair)
    print(indexes)

a = [10, 5, 2, 3, 7, 5]
target = 10
sum_pairs(a, target)

输出:

[(5, 5), (3, 7)]
[1, 5, 3, 4]

为了简化值的使用,我将 tuple 中的 tuple 解压为名称(xy 是“真实”值,ixx的索引,iyy的索引)。通过将索引附加到值,您总是确切知道它来自哪里,而不必猜测它。

您对 index 方法的使用无效,因为出于所有实际目的,您输入的两个 5 无法区分(在 CPython 上,由于小 int 优化,它们实际上是同一个对象),而 index 只是 returns 它找到的第一个(并且每次都必须不必要地重新扫描)。通过保持索引与关联值,您根本不必重新检查,您已经知道了。