标题(1)统计如下list单词及其出现的次数。
a=[‘apple’, ‘banana’, ‘apple’, ‘tomato’, ‘orange’, ‘apple’, ‘banana’, ‘watermeton’]
方法一:
利用字典。
a = [‘apple’, ‘banana’, ‘apple’, ‘tomato’, ‘orange’, ‘apple’, ‘banana’, ‘watermeton’]
dic = {}
for key in a:
dic[key] = dic.get(key, 0) + 1
print(dic)
输出结果:
1 {‘apple’: 3, ‘banana’: 2, ‘tomato’: 1, ‘orange’: 1, ‘watermeton’: 1}
方法二:
利用python的collections包。
from collections import Counter
a = [‘apple’, ‘banana’, ‘apple’, ‘tomato’, ‘orange’, ‘apple’, ‘banana’, ‘watermeton’]
d = Counter(a)
print(d)
输出结果:
1 Counter({‘apple’: 3, ‘banana’: 2, ‘tomato’: 1, ‘orange’: 1, ‘watermeton’: 1}) # 是一个类似字典的结构
标题(2)给列表中的字典排序:例如有如下list对象:
alist=[{“name”:“a”, “age”:20}, {“name”:“b”, “age”:30}, {“name”:“c”, “age”:25}] 将alist中的元素按照age从小到大排序。
利用list的内建函数,list.sort()来进行排序。
alist = [{“name”: “a”, “age”: 20}, {“name”: “b”, “age”: 30}, {“name”: “c”, “age”: 25}]
alist.sort(key=lambda x: x[‘age’])
print(alist)
这是一种效率很高的排序方法。
输出结果:
[{‘name’: ‘a’, ‘age’: 20}, {‘name’: ‘c’, ‘age’: 25}, {‘name’: ‘b’, ‘age’: 30}]