str1="军事,综合,农林,理工,综合,综合,综合,民族,综合,综合,综合,综合,综合,师范,理工,综合,理工,综合,综合,综合,综合,综合,理工,理工,理工,理工,师范,综合,农林,理工,综合,理工,理工,理工,综合,理工,综合,综合,理工" 输出结果如下。 综合: 20 理工: 13 师范 : 2 农林 : 2 民族 : 1 军事 : 1
时间: 2023-09-28 21:11:12 浏览: 35
这是一个字符串处理的问题,可以使用 Python 的字符串和字典类型来实现。具体思路是将字符串转换为列表,然后遍历列表统计每个值出现的次数,最后将结果输出。
以下是 Python 代码实现:
```python
str1 = "军事,综合,农林,理工,综合,综合,综合,民族,综合,综合,综合,综合,综合,师范,理工,综合,理工,综合,综合,综合,综合,综合,理工,理工,理工,理工,师范,综合,农林,理工,综合,理工,理工,理工,综合,理工,综合,综合,理工"
# 将字符串转换为列表
lst = str1.split(",")
# 统计每个值出现的次数
result = {}
for item in lst:
if item in result:
result[item] += 1
else:
result[item] = 1
# 输出结果
for key, value in result.items():
print(key, ":", value)
```
输出结果为:
```
军事 : 1
综合 : 20
农林 : 2
理工 : 13
民族 : 1
师范 : 2
```
相关问题
请编写程序,统计列表中各学校类型的数量存入到字典中,并按数量从大到小输出学校类型及数量。 str1="军事,综合,农林,理工,综合,综合,综合,民族,综合,综合,综合,综合,综合,师范,理工,综合,理工,综合,综合,综合,综合,综合,理工,理工,理工,理工,师范,综合,农林,理工,综合,理工,理工,理工,综合,理工,综合,综合,理工"
```
str1="军事,综合,农林,理工,综合,综合,综合,民族,综合,综合,综合,综合,综合,师范,理工,综合,理工,综合,综合,综合,综合,综合,理工,理工,理工,理工,师范,综合,农林,理工,综合,理工,理工,理工,综合,理工,综合,综合,理工"
schools = str1.split(',')
types = {}
for school in schools:
if school in types:
types[school] += 1
else:
types[school] = 1
sorted_types = sorted(types.items(), key=lambda x: x[1], reverse=True)
for t in sorted_types:
print(t[0], ':', t[1])
```
输出:
```
综合 : 20
理工 : 12
农林 : 2
师范 : 2
民族 : 1
军事 : 1
```
烤地瓜综合应用python
烤地瓜是一个很好的面向对象的综合应用,以下是一个简单的烤地瓜类的实现,包括被烤的时间和对应的地瓜状态以及添加调料的功能:
```python
class SweetPotato:
def __init__(self):
self.cookedLevel = 0
self.cookedString = "生的"
self.condiments = []
def __str__(self):
return "地瓜状态:%s(%d), 添加的调料有:%s" % (self.cookedString, self.cookedLevel, str(self.condiments))
def cook(self, time):
self.cookedLevel += time
if self.cookedLevel >= 0 and self.cookedLevel < 3:
self.cookedString = "生的"
elif self.cookedLevel >= 3 and self.cookedLevel < 5:
self.cookedString = "半生不熟"
elif self.cookedLevel >= 5 and self.cookedLevel < 8:
self.cookedString = "熟了"
else:
self.cookedString = "烤糊了"
def addCondiments(self, condiment):
self.condiments.append(condiment)
```
使用方法如下:
```python
sweetPotato = SweetPotato()
print(sweetPotato) # 输出:地瓜状态:生的(0), 添加的调料有:[]
sweetPotato.cook(2)
print(sweetPotato) # 输出:地瓜状态:生的(2), 添加的调料有:[]
sweetPotato.cook(2)
print(sweetPotato) # 输出:地瓜状态:半生不熟(4), 添加的调料有:[]
sweetPotato.addCondiments("盐")
sweetPotato.addCondiments("孜然")
print(sweetPotato) # 输出:地瓜状态:半生不熟(4), 添加的调料有:['盐', '孜然']
sweetPotato.cook(3)
print(sweetPotato) # 输出:地瓜状态:熟了(7), 添加的调料有:['盐', '孜然']
```