python - 如果列表中的数字等于n,则打印出它们的索引

标签 python

任务:

You are given two parameters, an array and a number. For all the numbers that make n in pairs of two, return the sum of their indices.

input is: arr = [1, 4, 2, 3, 0, 5] and n = 7

output: 11

since the perfect pairs are (4,3) and (2,5) with indices 1 + 3 + 2 + 5 = 11

到目前为止,我已经有了这个,它可以打印出完美的配对

from itertools import combinations


def pairwise(arr, n):    
    for i in combinations(arr, 2): # for index in combinations in arr, 2 elements
        if i[0] + i[1] == n: # if their sum is equal to n
            print(i[0],i[1])

输出:

4,3 2,5

但是,有人有关于如何打印完美对的索引的提示吗?我应该使用 numpy 还是应该更改整个函数?

最佳答案

您可以生成索引组合,而不是生成数组元素的组合。

from itertools import combinations


def pairwise(arr, n):
    s = 0 
    for i in combinations(range(len(arr)), 2): # for index in combinations in arr, 2 elements
        if arr[i[0]] + arr[i[1]] == n: # if their sum is equal to n
            # print(arr[i[0]],arr[i[1]])
            # print(i[0],i[1])
            s += i[0] + i[1]
    # print(s)
    return s

关于python - 如果列表中的数字等于n,则打印出它们的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49976015/

相关文章:

python - 从中间的 pandas df 读取行

任意行上的 Python Sphinx anchor

python - 相同的两个模型之间的两个一对多关系

python - 验证 Twitter 时无法收到 Twitter 电子邮件

Python:查找字符串中字符的值

python - 为什么生成器更快?

python - '上下文'对象没有属性 'stdout_capture'

python - 如何查找所有 Python 内置私有(private)变量,如 __file__、__name__

python - 在 Python 中使用 OpenCV 从图像中裁剪人脸

python - Scrapy:为什么我的响应对象没有 body_as_unicode 方法?