我試圖創建一個函數等於列表中的其他數字的總和。例如,如果列表是[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