python - 打印出以 's' 开头的单词时,我的 jupyter 笔记本没有响应是代码错误还是笔记本问题?

标签 python jupyter-notebook

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

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']

关于python - 打印出以 's' 开头的单词时,我的 jupyter 笔记本没有响应是代码错误还是笔记本问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56441815/

相关文章:

python - 使用 Python 从文本文件中读取特定的列值

jupyter-notebook - 导入错误: cannot import name 'STL' from 'statsmodels.tsa.seasonal'

jupyter-notebook - 当我加载太多数据时,JupyterLab 内核会重新启动

python - 稀疏数据的 3D 数组与稀疏矩阵

python - 如何在不知道路径的情况下从另一个相对文件夹导入?

python - 在 Python 的 Numpy 中,点积不等同于 einsum,我不确定为什么不

python - Ipython 笔记本 : Open & Edit Files

python - 在 Jupyter Notebook 上的 Pandas Dataframe 中显示多个空格的方法

ipython - 从命令行在浏览器中打开.ipynb

python - 寻找方程的数值解