[英]Python performing calculation in a list
I have this list [9,4,5]
I want to multiply each element by 2 then I sum the result I will get 9*2=18,4*2=8,5*2=10
then I sum 18+8+10=36
我有这个列表
[9,4,5]
我想将每个元素乘以 2 然后我总结结果我会得到9*2=18,4*2=8,5*2=10
然后我总结18+8+10=36
Can you guys help me to write this please你们能帮我写这个吗
There is no need to multiply each element by 2;不需要将每个元素乘以 2; just multiply the whole sum by 2 afterwards.
之后只需将整个总和乘以 2。
>>> data = [9, 4, 5]
>>> 2 * sum(data)
36
sum()
和列表理解
sum([x*2 for x in your_list])
You can use sum and a generator expression:您可以使用 sum 和生成器表达式:
>>> data = [9,4,5]
>>> sum(n*2 for n in data)
36
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.