Skip to main content
 首页 » 编程设计

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

2024年09月07日8shangdawei

任务:

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