![](/img/trans.png)
[英]Why is my index out of range? IndexError: list index out of range
[英]IndexError : list index out of range Please let me know why isnt my code working
下面的问题是使用.split()
打印所有以s
开头的单词,如果在下面给出的语句(st)
,我编写的代码由于某种原因不起作用,它说indexerror
。
这是我的代码
st = 'Print only the words that start with s in this sentence'
x=st.split()
i=0
j=0
for y in x:
i+=1
if x[i][j]=='s':
print(y)
我收到的错误
that
with
this
回溯(最近一次调用) IndexError:列表索引超出范围
为什么that
, with
this
的字样谁能解释一下?
我的教授显然发布的理想代码是
st = 'Print only the words that start with s in this sentence'
for word in st.split():
if word[0] == 's':
print(word)
我不太明白他的代码和我的代码之间的区别,我的实际意思是我只是将.split()
引用到我的代码中的变量x
并使用了另外两个变量i,j
来检查代码的第一个字母list x
,请帮助我理解出了什么问题。
st = 'Print only the words that start with s in this sentence'
x=st.split()
# x = ['Print', 'only', 'the', ...] you are actually spliting the sentence into
# indvidual words
i=0
j=0
# now when you loop this list
for y in x:
# y = 'Print' , second time y = 'only'
i+=1
# x[1][0] i.e i = 1 , j= 0 , you miss the first value and at last pass i=11 , but the maximim allowed index is 10 as len(x) = 11, as index starts from 0 so 11-1 is the maximum allowed index
if x[i][j]=='s':
print(y)
在 if 语句之后移动 i+=1,在循环结束时
for y in x:
if x[i][j]=='s':
print(y)
i+=1
i 和 j 没有任何作用,因为 y 包含单个单词,因此当 y = 'Print'、y[0] = P 等第一次使用 y[0] 代替 x[i][j] 时
for y in x:
if y[0]=='s':
print(y)
如您所见,您的代码与教授的代码相似。 唯一的事情是,根据他的经验,他知道拆分返回一个元素列表,我们在一个列表上循环,因此他合并了两个语句,即 x = st.split() 和 for y in x 合二为一。
for word in st.split(): # for words in ["Print", "only", "the", "words" ...]
if word[0] == 's':
print(word)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.