python - 打印以'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)
解决方案
如果列表中的第一个单词不以 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']
推荐阅读
- java - 如何强制 Spring Security HTTP 过滤器的顺序?
- python-3.x - Python Webserver 无法启动
- java - Android:在启动地图活动时,在 onCreate 方法之前调用 onMapReady
- python - 使用 Numpy 过滤数组字符串
- python - Python3 中的错误处理 - 在单词列表中查找特定字母的位置
- java - 我想从网站获取内容(HTML),在运行应用程序时出现此运行时错误,我无法解决此问题
- odoo - 不能在 attrs 中使用 many2many 字段?
- excel - 查找所有通过粘贴或拖动更改的单元格
- selenium - 如何创建添加日志消息的 BaseClass
- powerbi - DAX - 作为 SUMX 输出的文本