首页 > 解决方案 > 打印以's'开头的单词时,我的jupyter笔记本没有响应是代码错误还是笔记本问题?

问题描述

在运行代码以打印以“s”开头的单词时,jupyter 笔记本没有响应

st = 'Print only the words that start with s in this s'
lis=st.split()
i=0
res=[]
while i<len(lis):
    if lis[i][0]=='s':
        res.append(list[i])
        i+=1
print(res)

标签: pythonjupyter-notebook

解决方案


如果列表中的第一个单词不以 s 开头,则您的代码会卡住,将 i 增量更改为 if 如下所示:

st = 'Print only the words that start with s in this s'
lis=st.split()
i=0
res=[]
while i<len(lis):
    if lis[i][0]=='s':
        res.append(list[i])
    i+=1
print(res)

编辑:此代码的改进版本

st = 'Print only the words that start with s in this s'
res=[]
for s in st.split():
    if s[0] == 's':
        res.append(s)

print(res)

您还可以使用列表推导

st = 'Print only the words that start with s in this s'
res = [s for s in st.split() if s[0] == 's']
print(res)
# prints ['start', 's', 's']

推荐阅读