我试图创建一个函数等于列表中的其他数字的总和。例如,如果列表是[0,1,2,3,4,5],则函数应该等于5 + 3 + 1。我怎么能这样做?我对Python的知识并没有比while和for循环更远。谢谢。创建奇数索引的总和python
2
A
回答
5
下面是一个简单的一行:
In [37]: L
Out[37]: [0, 1, 2, 3, 4, 5]
In [38]: sum(L[1::2])
Out[38]: 9
在上面的代码,L[1::2]
说:“在L
获得有史以来第二个元素,索引1开始”
这里是一个办法做到所有繁重的自己:
L = [0, 1, 2, 3, 4, 5]
total = 0
for i in range(len(L)):
if i%2: # if this is an odd index
total += L[i]
这里的另一种方式,用enumerate
:
L = [0, 1, 2, 3, 4, 5]
total = 0
for i,num in enumerate(L):
if i%2:
total += num
0
>>> arr = [0,1,2,3,4,5]
>>> sum([x for idx, x in enumerate(arr) if idx%2 != 0])
9
这仅仅是一个列表理解仅包括在arr
具有奇数索引的元素。
为了说明在传统的for
循环:
>>> my_sum = 0
>>> for idx, x in enumerate(arr):
... if idx % 2 != 0:
... my_sum += x
... print("%d was odd, so %d was added. Current sum is %d" % (idx, x, my_sum))
... else:
... print("%d was even, so %d was not added. Current sum is %d" % (idx, x, my_sum))
...
0 was even, so 0 was not added. Current sum is 0
1 was odd, so 1 was added. Current sum is 1
2 was even, so 2 was not added. Current sum is 1
3 was odd, so 3 was added. Current sum is 4
4 was even, so 4 was not added. Current sum is 4
5 was odd, so 5 was added. Current sum is 9
相关问题
- 1. 如何在Python中找到位于奇数索引处的元素总和
- 2. Javascript - 创建数组索引和访问
- 3. 索引总和列
- 4. 创建数据库索引Vs用户为表创建索引
- 5. 创建索引数据帧
- 6. 创建索引
- 7. 奇的地方数总和
- 8. 奇怪的python索引CSV文件
- 9. 总结一个数组元素的奇怪索引
- 10. Zend的工具CLI总是创建索引操作索引视图
- 11. 创建PK和索引后的索引假脱机?
- 12. 在python中创建计数器的索引问题
- 13. 创建索引Nest
- 14. 索引未创建
- 15. postgres创建索引
- 16. 创建索引MATLAB
- 17. 创建索引列
- 18. MySQL索引创建
- 19. 如何在python中创建一个数据框的索引和值的列表
- 20. Kibana创建索引模式:通配符的奇怪行为
- 21. Python创建新的数据帧分组和总结列
- 22. Oracle:创建基于函数的索引
- 23. 创建索引 - MongoDB的
- 24. 创建索引的性能
- 25. 创建索引的资格
- 26. 创建索引的顺序
- 27. 创建MySQL的索引
- 28. 索引视图索引创建失败
- 29. 创建重复值的计数总和
- 30. 出于好奇:哪个更适合创建总和?总和(列表)与积累
'总和(L [1 :: 2])'。 – inspectorG4dget