使用列表的元素作为指数的2 ^ x的总和

时间:2015-10-30 11:07:44

标签: python list exponent

给定一个包含整数的列表:

>>> print mylist
[0, 1, 2]

我可以计算2^0 + 2^1 + 2^2的总和吗?基数(2)是固定的,它不会改变,我只是使用列表的元素作为指数

相关疑惑:

列表是否适合我尝试做的事情?

6 个答案:

答案 0 :(得分:5)

当然是。

mylist = [0, 1, 2]
print sum([2**x for x in mylist])

输出:

7

答案 1 :(得分:2)

mylist = [0,1,2]
mysum = 0
for i in mylist:
    mysum = mysum + 2**i


>>> print mysum
7

答案 2 :(得分:1)

您只需将map()lambda表达式用作:

print sum(map(lambda x:2**x, mylist))
>>> 7

答案 3 :(得分:0)

我猜你可以使用10:56:00.064 INFO - Analysing C:\A\Projekte\sqs\git\build\sonar\de.kvb.sqs_admin-db\jacoco-overall.exec 10:56:00.116 INFO - No information about coverage per test. 10:56:00.116 INFO - Sensor JaCoCoOverallSensor done: 116 ms ... 10:56:00.718 INFO - Sensor JaCoCoSensor... 10:56:00.720 INFO - Analysing C:\A\Projekte\sqs\git\build\jacoco\jacoco.exec 10:56:00.738 INFO - No information about coverage per test. ... 10:56:06.442 INFO - Analysing C:\A\Projekte\sqs\git\build\sonar\de.kvb.sqs_admin-gui\jacoco-overall.exec 10:56:06.453 INFO - No information about coverage per test. 10:56:06.453 INFO - Sensor JaCoCoOverallSensor done: 31 ms ... 10:56:06.833 INFO - Sensor JaCoCoSensor... 10:56:06.837 INFO - Analysing C:\A\Projekte\sqs\git\build\jacoco\jacoco.exec 10:56:06.863 INFO - No information about coverage per test. ,但是,鉴于其元素的线性特性,使用list对象可能更好:

range()

答案 4 :(得分:0)

不使用列表的另一种方法是:

x=0 for i in range(0,3): x= x + pow(2,i) print "%d" % x

答案 5 :(得分:-3)

尝试

mylist = [0,1,2]
sum(2**i for i in mylist)