编写程序:使用3种方法实现将字词组成的列表lst=['apple','orange','pink','peach','banana','book’] 根据首字母分类为包含列表的字典
时间: 2023-07-15 15:13:01 浏览: 62
方法一:
```
lst = ['apple', 'orange', 'pink', 'peach', 'banana', 'book']
d = {}
for word in lst:
if word[0] in d:
d[word[0]].append(word)
else:
d[word[0]] = [word]
print(d)
```
方法二:
```
lst = ['apple', 'orange', 'pink', 'peach', 'banana', 'book']
d = {}
for word in lst:
d.setdefault(word[0], []).append(word)
print(d)
```
方法三:
```
from collections import defaultdict
lst = ['apple', 'orange', 'pink', 'peach', 'banana', 'book']
d = defaultdict(list)
for word in lst:
d[word[0]].append(word)
print(dict(d))
```
相关问题
编写代码实现:删除列表中大于5的元素,lst = [2, 5, 6, 7, 3, 4, 10]
可以用列表推导式来实现删除大于5的元素:
```python
lst = [2, 5, 6, 7, 3, 4, 10]
lst = [x for x in lst if x <= 5]
print(lst)
```
运行结果为:
```
[2, 5, 3, 4]
```
也可以用循环和条件判断来实现:
```python
lst = [2, 5, 6, 7, 3, 4, 10]
new_lst = []
for x in lst:
if x <= 5:
new_lst.append(x)
print(new_lst)
```
运行结果也为:
```
[2, 5, 3, 4]
```
lst = ['apple', None, 'banana', '', 'orange', ' ', ' ' ]Python去除空元素
要去除lst列表中的空元素,可以使用列表推导式和if语句来实现。代码如下:
lst = ['apple', None, 'banana', '', 'orange', ' ', ' ']
new_lst = [x for x in lst if x and x.strip()]
print(new_lst)
输出结果为:['apple', 'banana', 'orange']
解释:上述代码中,if语句用于判断元素是否为空或者只包含空格,如果是,则不加入新列表中。