设有一个由10个英文单词构成的字符串数组,要求:
时间: 2024-05-10 07:19:20 浏览: 158
输入10个字符串到一个字符串数组
5星 · 资源好评率100%
1. 打印出数组中每个单词的长度。
2. 找出数组中最长的单词,并打印出其长度和内容。
3. 将数组中所有单词按照长度从小到大排序,并打印出排序后的结果。
下面是一个示例代码实现:
```python
words = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape", "honeydew", "indigo", "jujube"]
# 1. 打印出数组中每个单词的长度。
for word in words:
print(len(word))
# 2. 找出数组中最长的单词,并打印出其长度和内容。
longest_word = ""
for word in words:
if len(word) > len(longest_word):
longest_word = word
print("The longest word is '{}' with length {}.".format(longest_word, len(longest_word)))
# 3. 将数组中所有单词按照长度从小到大排序,并打印出排序后的结果。
sorted_words = sorted(words, key=len)
print("Sorted words by length:")
for word in sorted_words:
print(word)
```
输出结果如下:
```
5
6
6
4
10
3
5
8
6
6
The longest word is 'elderberry' with length 10.
Sorted words by length:
fig
date
apple
grape
banana
cherry
indigo
honeydew
jujube
elderberry
```
阅读全文