IndexError:列表索引超出范围请让我知道为什么我的代码不起作用

时间:2019-07-26 04:25:30

标签: python jupyter-notebook

以下问题是使用s打印所有以.split()开头的单词,因为如果在下面给出的语句(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:列表索引超出范围

为什么显示thatwiththis这两个词,任何人都可以解释吗?

我的教授显然发布的理想代码是

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并使用了另外两个变量{{ 1}},以检查i,j的第一个字母,请帮助我了解问题所在。

1 个答案:

答案 0 :(得分:2)

您的代码:

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 [0]代替x [i] [j],即,当y ='Print'时第一次使用y [0] = P等等

for y in x:    
 if y[0]=='s':
    print(y)

您教授的代码:

如您所见,您的代码看起来与教授的代码相似。唯一的是,根据他的经验,他知道拆分会返回一个元素列表,并且我们在列表上循环,因此他将两个语句(即x = st.split())和x中的y合并为一个。

for word in st.split(): # for words in ["Print", "only", "the", "words" ...]

 if word[0] == 's':

  print(word)
相关问题