如何获取对象中包含的每个项目的单个字符数

发布于 2025-01-14 00:14:12 字数 372 浏览 4 评论 0原文

我正在尝试使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

桃扇骨 2025-01-21 00:14:12

len() 报告列表的长度 - 如果列表中有 1 个项目,则其长度为 1 - 该元素的 索引 为 0。

len(['one element']) == 1

索引为基于 0:

 k = ['one element']
 k[0] == "one element"

您使用 (0, len(d)) 元组:len(d) 比您的最大可能索引大 1 em> 列表,因为索引从 0 开始。

for i in (0,len(d)): # (0,2)
    print(len(d[i])) # d[2] 超出索引

因此:列表索引超出范围

使用range(len(d))代替 - 甚至更好:

for element in d:
    print(len(element))   # to print all

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.

len(['one element']) == 1

Indexing is 0 based:

 k = ['one element']
 k[0] == "one element"

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.

for i in (0,len(d)):    # (0,2)
    print(len(d[i]))    # d[2] is out of index

Hence: list index out of range

Use range(len(d)) instead - or even better:

for element in d:
    print(len(element))   # to print all
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文