两个列表,求特别几位数的平均值

给出两个数字列表A和B,其中A包含自然数,B包含整数。编写一个函数average(A, B),计算A中元素在B中元素索引的位置上的平均值(四舍五入到小数点后一位)。然后该函数应将A中可索引元素的平均值返回给调用者。你可以假设B的元素是唯一的。
例子
假设A=[1,2,3],B=[0,1]:结果应该是(A[0]+A[1])/2=(1+2)/2=1.5

def average(A, B):
    # put your code after this line  

    # do not edit after this line

def main():
    A = list(map(float, input().split()))
    B = list(map(int, input().split()))
    
    print(average(A, B))



if __name__ == "__main__":
    main()

以下是可以实现该需求的代码:

def average(A, B):
    total = 0
    count = 0
    
    for b in B:
        if b < len(A) and b >= 0:
            total += A[b]
            count += 1
    
    if count > 0:
        return round(total/count, 1)
    else:
        return 0.0


def main():
    A = list(map(float, input().split()))
    B = list(map(int, input().split()))
    
    print(average(A, B))


if __name__ == "__main__":
    main()

函数average(A, B)的实现思路是:遍历列表B中的元素,判断它是否可以作为索引访问列表A中的元素,如果可以,则将对应的元素值累加到total中,并将计数器count加1。最后,如果count大于0,则计算平均值并返回;否则返回0.0。

在main()函数中,首先读取输入的列表A和B,然后调用average(A, B)函数计算平均值,并将结果打印输出。


def average(A, B):
    list1 = [A[x] for x in B if x < len(A)]
    if len(list1) > 0:
        ave = sum(list1) / len(list1)
        return ave
    else:
        print('无法建立对应索引')


def main():
    A = list(map(float, input().split()))
    B = list(map(int, input().split()))
    print(A)
    print(B)
    print(average(A, B))


if __name__ == "__main__":
    main()

结果为:

1 2 3
0 1
[1.0, 2.0, 3.0]
[0, 1]
1.5

以下是Python的解法:

def average(A, B):
    sum = 0
    count = 0
    for i in B:
        if i >= len(A) or i < 0:
            continue
        sum += A[i]
        count += 1
    if count == 0:
        return 0
    else:
        return round(sum/count, 1)

def main():
    A = list(map(float, input().split()))
    B = list(map(int, input().split()))
    
    print(average(A, B))

if __name__ == "__main__":
    main()


在函数average()中,我们遍历列表B,计算B中每个元素在列表A中的索引,如果该索引超出了A的范围,则跳过该元素。否则,我们将A中对应元素的值加入总和中,并将计数器加1。最后,如果计数器不为0,则返回平均值;否则返回0。

列表可以用负数索引的,B列表要求整数,那么负数也是有可能的,所以参考
代码如下:

def average(A, B):
    # put your code after this line  
    sum = 0
    for i in B:
        if i >= len(A) or ( i<0 and i*-1>len(A)):
            print("索引超出列表的长度")
            return
        sum = sum + A[i]
    result = format(sum/len(B),'.1f')
    return result
    
    # do not edit after this line
 
def main():
    A = list(map(float, input().split()))
    B = list(map(int, input().split()))
    
    print(average(A, B))
 
 
 
if __name__ == "__main__":
    main()

测试:

img