我試圖創建一個函數等於列表中的其他數字的總和。例如,如果列表是[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. 總結一個數組元素的奇怪索引
- 9. Zend的工具CLI總是創建索引操作索引視圖
- 10. 創建索引列
- 11. 索引未創建
- 12. MySQL索引創建
- 13. 如何在python中創建一個數據框的索引和值的列表
- 14. Kibana創建索引模式:通配符的奇怪行爲
- 15. Python創建新的數據幀分組和總結列
- 16. Oracle:創建基於函數的索引
- 17. 索引視圖索引創建失敗
- 18. 創建索引 - MongoDB的
- 19. 創建索引的順序
- 20. 創建索引的資格
- 21. 出於好奇:哪個更適合創建總和?總和(列表)與積累
- 22. Liquibase總是生成創建/刪除索引的變更集
- 23. 如何打印字符串的偶數索引和奇數索引字符?
- 24. 奇怪的Python的numpy的數組索引行爲
- 25. cassandra創建和使用索引[pycassa]
- 26. MongoDB和Rails:如何創建索引
- 27. 將0添加到Python中的2D raay的奇數索引中
- 28. 創建索引而不鍵入整數:Python
- 29. 從DataFrame到父索引的總和值 - Python/Pandas
- 30. 奇怪的列表和索引行爲
'總和(L [1 :: 2])'。 – inspectorG4dget