如何将列表的值与其索引的幂相加

How to sum the values of list to the power of their indices

提问人:BlueMoon93 提问时间:11/17/2016 最后编辑:BlueMoon93 更新时间:11/17/2016 访问量:900

问:

如何将 list 的值与它们的索引的幂相加?Python 3

例:

[3, 0, 2] = 3^1 + 0^2 + 2^3 = 11

这个想法是为列表中任何可能的非负数组合创建一个唯一的索引。这样,我就可以使用列表来计算某物的索引。


编辑:虽然问题已经得到回答,但我刚刚意识到该方法不会为列表中非负整数的任何组合创建唯一索引。为此,假设是可能的整数数,并基于公认的答案,a

sum(a ** i * j for i,j in enumerate(l, 0))

这个想法是,每个数字都会使索引增加一个与其在列表中的位置成指数成正比的量。假设 (from to ),上面的例子变为a=403

[3, 0, 2] = 4^0*3 + 4^1*0 + 4^2^2 = 35

其中,索引的范围为 。04^3-1=63

列表 python-3.x

评论

0赞 Dimitris Fasarakis Hilliard 11/17/2016
嗯,编辑可能会更令人困惑,因为它会有所帮助(关于原始问题和答案)。另外,不需要:-) 默认情况下,索引从 开始。enumerate(list, 0)enumerate(list)0

答:

8赞 Dimitris Fasarakis Hilliard 11/17/2016 #1

使用 enumerate 获取索引并将其提供给 sum

sum(j ** i for i,j in enumerate(l, 1))

将参数指定为 as 可确保索引将从(根据需要)而不是从(您通过普通获得的默认值)开始:startenumerate110enumerate

>>> l = [3, 0, 2]    
>>> sum(j ** i for i,j in enumerate(l, 1))
11

在函数精神上,您还可以使用带有 count 的 map 作为要映射的函数,这些 itertoolspow 传入:

>>> from itertools import count
>>> sum(map(pow, l, count(1)))
11

这些几乎在大约相同的时间内执行;生成器表达式 to 虽然提供了灵活性的轻微优势。sum

1赞 P. Camilleri 11/17/2016 #2

你可以用numpy来做到这一点,这通常比遍历列表更快:

In [1]: import numpy as np

In [2]: l = [0, 3, 4, 1]

In [3]: np.array(l) ** np.arange(len(l))
Out[3]: array([ 1,  3, 16,  1])

In [4]: np.array(l) ** np.arange(1, len(l) + 1)
Out[4]: array([ 0,  9, 64,  1])