如何获取对象中包含的每个项目的单个字符数
我正在尝试使用 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
谁能解释这个错误从何而来以及如何修复它?
I am trying using a for loop to count the characters within this object:
S = "Hello World"
d = S.split()
d
['Hello', 'World']
for i in (0,len(d)):
print(len(d[i]))
However, I got the following error.
Traceback (most recent call last):
File "<pyshell#26>", line 2, in <module>
print(len(n[i]))
IndexError: list index out of range
Could anyone explain where this error come from and how to possibly fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
len()
报告列表的长度 - 如果列表中有 1 个项目,则其长度为 1 - 该元素的 索引 为 0。索引为基于 0:
您使用
(0, len(d))
元组:len(d)
比您的最大可能索引大 1 em> 列表,因为索引从 0 开始。因此:
列表索引超出范围
使用
range(len(d))
代替 - 甚至更好:len()
reports the length of the list - if there is 1 item in the list, it is of length 1 -- the index of that element is 0.Indexing is 0 based:
You use a tuple of
(0, len(d))
:len(d)
is 1 bigger then the biggest possible index of your list because indexing starts at 0.Hence:
list index out of range
Use
range(len(d))
instead - or even better: