我正在嘗試使用 for 回圈來計算此物件中的字符:
S = "Hello World"
d = S.split()
d
['Hello', 'World']
for i in (0,len(d)):
print(len(d[i]))
但是,我收到以下錯誤。
Traceback (most recent call last):
File "<pyshell#26>", line 2, in <module>
print(len(n[i]))
IndexError: list index out of range
誰能解釋這個錯誤來自哪里以及如何解決它?
uj5u.com熱心網友回復:
len()報告串列的長度 - 如果串列中有 1 個專案,則它的長度為 1 - 該元素的索引為 0。
len(['one element']) == 1
索引是基于 0 的:
k = ['one element']
k[0] == "one element"
您使用的元組(0, len(d)):比串列中len(d)可能的最大索引大 1,因為索引從 0 開始。
for i in (0,len(d)): # (0,2) print(len(d[i])) # d[2] is out of index
因此:list index out of range
改為使用range(len(d))- 甚至更好:
for element in d:
print(len(element)) # to print all
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/445062.html
上一篇:如何滾動過濾?
