gpt4 book ai didi

Python 幂和指数

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

将一系列数字乘以指定数量的指数的最佳实现是什么。

目前我有一个包含 8 个数字的列表,需要这些数字进行幂运算。每个列表将始终包含 8 个数字,并且列表中的数字将始终具有其索引值所在的指数。

例如:

List = [1,2,3,4,5,6,7,8]

Power(1,0) + Power(2,1) + Power(3,2) +.... Power(8,7)

但是,问题是如果列表没有值,如何在不影响总和的情况下携带指数增加的值。

示例:

List = [1,None,3,4,5,6,7,8]

Power(1,0) + (none) + Power(3,2) +.... Power(8,7)

任何实现想法都会有所帮助。

最佳答案

也许这样的事情可以让你开始?

import numpy as np

l = [1, None, 3, 4, 5, 6, 7, 8]

# If you need to define the powers
# powers = [0, 1, 2, 3, 4, 5, 6, 7]

powers = np.arange(len(l)) # If powers are always indices

arr = np.array([x if x is not None else 0 for x in l])

arr**powers
# array([ 1, 0, 9, 64, 625, 7776, 117649, 2097152]

(arr**powers).sum()
# 2223276
<小时/>

再想一想,如果您有 [None, 1, 2, 3],因为 0**0=1。所以我们可能应该选择类似的东西

l = [1, None, 3, 4, 5, 6, 7, 8]

numbers = np.array([x for x in l if x is not None])
powers = np.array([i for i in range(len(l)) if l[i] is not None])
(numbers**powers).sum()

关于Python 幂和指数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53934243/

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