py用字典和集合结构统计列表中食物的数量,food =["apple","orange","grape", "apple","orange","apple", "tomato", "potato","grape"],输出各种食物及数量。
时间: 2023-11-06 19:06:52 浏览: 62
可以使用字典来统计列表中食物的数量,代码如下:
```
food = ["apple", "orange", "grape", "apple", "orange", "apple", "tomato", "potato", "grape"]
food_dict = {}
for f in food:
if f in food_dict:
food_dict[f] += 1
else:
food_dict[f] = 1
for k, v in food_dict.items():
(k, v)
```
输出结果为:
```
apple 3
orange 2
grape 2
tomato 1
potato 1
```
其中,字典food_dict的键为食物名称,值为该食物在列表中出现的次数。使用for循环遍历字典,输出各种食物及数量。
相关问题
用字典和集合结构统计列表中食物的数量,food =["apple","orange","grape", "apple","orange","apple", "tomato", "potato","grape"],输出各种食物及数量
可以使用Python中的字典和集合结构来统计列表中食物的数量。具体步骤如下:
1. 首先,将列表转换为集合,这样可以去除列表中的重复元素,只保留不同种类的食物。
2. 然后,遍历集合中的每个元素,在列表中统计该元素出现的次数,并将结果存储在字典中。
3. 最后,遍历字典中的每个键值对,输出各种食物及其数量。
下面是代码实现:
```
food = ["apple", "orange", "grape", "apple", "orange", "apple", "tomato", "potato", "grape"]
# 将列表转换为集合
food_set = set(food)
# 统计各种食物的数量
food_dict = {}
for item in food_set:
count = food.count(item)
food_dict[item] = count
# 输出各种食物及其数量
for key, value in food_dict.items():
print(key, ":", value)
```
输出结果为:
```
tomato : 1
orange : 2
potato : 1
grape : 2
apple : 3
```
将列表fruits=["apple", "orange", "grape"]中添加一个新元素"banana",执行语句为
你可以使用列表的append()方法将新元素添加到列表末尾,执行语句如下:
```python
fruits = ["apple", "orange", "grape"]
fruits.append("banana")
print(fruits) # 输出:['apple', 'orange', 'grape', 'banana']
```