【问题标题】:IndexError : list index out of range Please let me know why isnt my code workingIndexError:列表索引超出范围请告诉我为什么我的代码不起作用
【发布时间】:2019-07-26 04:25:30
【问题描述】:

以下问题是使用.split() 打印所有以s 开头的单词,因为如果在下面给出的语句(st) 中,我编写的代码由于某种原因不起作用,它说@ 987654324@.

这是我的代码

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                             

Traceback(最近一次调用最后一次) 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 并使用其他2 个变量i,j 来检查list x 的第一个字母,请帮助我了解问题所在。

【问题讨论】:

  • 试着用纸笔写一遍,在每一步写下每个变量的值……
  • print('\n'.join(word for word in st.split() if word.startswith('s')))。它有split()、for 和if。
  • 将i+=1移动到for循环的末尾,最好尝试通过打印每一步的值来调试你的代码,在每一步检查x,y,i,x[i][j]的值,你会明白更多。跨度>

标签: python jupyter-notebook


【解决方案1】:

您的代码:

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)

在您的代码中正确

将 i+=1 移动到 if 语句之后,循环结束处和

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() 和 for y in x 合并为一个。

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

 if word[0] == 's':

  print(word)


 

【讨论】:

  • @sourabh 有什么理由回答被接受然后不被接受?
猜你喜欢
  • 2018-06-05
  • 1970-01-01
  • 1970-01-01
  • 2016-10-20
  • 2011-11-30
  • 1970-01-01
  • 2019-01-06
  • 1970-01-01
  • 2018-02-04
相关资源
最近更新 更多