【发布时间】: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]的值,你会明白更多。跨度>