综合地写这个陈述
Write this statement in a comprehensive way
我开始学习 Python 和一般编程。在进行语句评估测试时,我 运行 遇到了一个对我来说毫无意义的语法问题。我在第二个 for.
中收到语法错误
谢谢!
st = 'Print only the words that start with s in this sentence'
listst = st.split()
for word in listst:
if word[0] == 's':
print(word)
#in one sentence?
startwiths = [word if word[0] == 's' for word in listst]
试试这个:
startwiths = [word for word in listst if word[0] == 's']
可以在 python 中找到有关列表理解的更多信息 here
if
语句位于列表理解的末尾。所以将你的最后一行重写为:
startwiths = [word for word in listst if word[0] == 's']
您还可以通过将 word[0] == 's'
替换为内置字符串 startswith
函数来进一步简化代码:
startwiths = [word for word in listst if word.startswith('s')]
希望对您有所帮助!
list_comp=[word for word in listst if word.lower()[0]=='s']
您也可以使用.startswith
list_comp=[word for word in listst if word.lower().startswith('s')]
我开始学习 Python 和一般编程。在进行语句评估测试时,我 运行 遇到了一个对我来说毫无意义的语法问题。我在第二个 for.
中收到语法错误谢谢!
st = 'Print only the words that start with s in this sentence'
listst = st.split()
for word in listst:
if word[0] == 's':
print(word)
#in one sentence?
startwiths = [word if word[0] == 's' for word in listst]
试试这个:
startwiths = [word for word in listst if word[0] == 's']
可以在 python 中找到有关列表理解的更多信息 here
if
语句位于列表理解的末尾。所以将你的最后一行重写为:
startwiths = [word for word in listst if word[0] == 's']
您还可以通过将 word[0] == 's'
替换为内置字符串 startswith
函数来进一步简化代码:
startwiths = [word for word in listst if word.startswith('s')]
希望对您有所帮助!
list_comp=[word for word in listst if word.lower()[0]=='s']
您也可以使用.startswith
list_comp=[word for word in listst if word.lower().startswith('s')]