def find_longest_word(s): words = s.split() longest_word = "" for word in words: if len(word) > len(longest_word): longest_word = word return longest_words = "This is a sample string for testing"longest_word = find_longest_word(s)print("The longest word in the string is:", longest_word)优化这段代码
时间: 2023-05-19 22:01:58 浏览: 56
可以使用 Python 内置的 max 函数来简化代码,如下所示:
def find_longest_word(s):
words = s.split()
longest_word = max(words, key=len)
return longest_word
s = "This is a sample string for testing"
longest_word = find_longest_word(s)
print("The longest word in the string is:", longest_word)
这样可以避免使用循环和 if 语句,使代码更加简洁和高效。
相关问题
输入一句英文,输出最长单词。输入输出参考样例。 样例: 输入 Life is full of luck 输出 Life full luck
好的,我可以帮你写一个 Python 代码来实现这个功能,代码如下:
```python
def find_longest_word(sentence):
words = sentence.split() # 将句子拆分成单词
longest_word = max(words, key=len) # 找出最长的单词
return longest_word
# 测试代码
sentence = "Life is full of luck"
longest_word = find_longest_word(sentence)
print(longest_word)
```
你可以将以上代码复制到 Python 解释器中运行,结果输出为:
```
Life
```
如果你想要输出所有最长的单词,可以稍微修改一下代码,如下所示:
```python
def find_longest_word(sentence):
words = sentence.split() # 将句子拆分成单词
longest_length = max(len(word) for word in words) # 找出最长的单词长度
longest_words = [word for word in words if len(word) == longest_length] # 找出所有最长的单词
return longest_words
# 测试代码
sentence = "Life is full of luck"
longest_words = find_longest_word(sentence)
print(longest_words)
```
运行结果为:
```
['Life', 'full', 'luck']
```
这样就能输出所有最长的单词了。
编写程序找出已知字符串s中的最长单词。
可以使用以下代码实现:
```python
def find_longest_word(s):
words = s.split()
longest_word = ""
for word in words:
if len(word) > len(longest_word):
longest_word = word
return longest_word
s = "This is a sample sentence to find the longest word"
longest_word = find_longest_word(s)
print("The longest word in the string is:", longest_word)
```
输出结果为:
```
The longest word in the string is: sentence
```