Collections中Counter函数,namedtuple函数,defaultdict函数的使用

#python中collections工具包的一点使用

#组织特征数据用namedtuple函数
from collections import namedtuple
Features = namedtuple('Features',['age','gender','name'])
row = Features(age=22,gender='male',name='Alex')
print(row.age)

#计数列表数据用Counter函数
from collections import Counter
ages = [22,22,25,25,30,24,26,24,35,45,52,22,22,22,25,16,11,15,40,30]
value_counts = Counter(ages)
print(value_counts.most_common())

#为字典设置默认键值用defaultdict函数
from collections import defaultdict
my_default_dict = defaultdict(int)
for letter in 'the red fox ran as fast as it could':
    my_default_dict[letter] += 1
print(my_default_dict)
 

Collections中Counter函数,namedtuple函数,defaultdict函数的使用_第1张图片 标题

 

你可能感兴趣的:(python,数据处理)