Python合并多个list,并统计合并后list中各元素出现的个数
背景:数据库中字段存储为列表形式,需将该字段查询出来,并统计查询出来数据中,各个元素出现的个数
一、合并列表
1、直接相加
temp_list1 = [1,2,3]
temp_list2 = ['a','b','c']
result = temp_list1 + temp_list2
print(result)
[1, 2, 3, 'a', 'b', 'c']
2、extend()
temp_list1 = [1,2,3]
temp_list2 = ['a','b','c']
result = temp_list1.extend(temp_list2)
print(result)
print(temp_list1)
None
[1, 2, 3, 'a', 'b', 'c']
注意: 第二种方法比较简洁,会覆盖原始list
二、统计列表中元素个数
1、利用字典统计
temp_list = [5,3,4,7,1,3,2,7,0,9,1,3,5,2,3,2,5,6,7,9,4,5]
temp_dict = {}
for key in temp_list:
temp_dict[key] = temp_dict.get(key, 0) + 1
print("temp_dict:{}".format(temp_dict))
temp_dict:{5: 4, 3: 4, 4: 2, 7: 3, 1: 2, 2: 3, 0: 1, 9: 2, 6: 1}
2、利用内置库Counter类统计
from collections import Counter
temp_list = [5,3,4,7,1,3,2,7,0,9,1,3,5,2,3,2,5,6,7,9,4,5]
result = Counter(temp_list)
print(type(result))
print("result:{}".format(result))
<class 'collections.Counter'>
result:Counter({5: 4, 3: 4, 7: 3, 2: 3, 4: 2, 1: 2, 9: 2, 0: 1, 6: 1})
3、利用第三方库pandas统计
import pandas
temp_list = [5,3,4,7,1,3,2,7,0,9,1,3,5,2,3,2,5,6,7,9,4,5]
result = pandas.value_counts(temp_list)
print(type(result))
print("result:{}".format(result))
<class 'pandas.core.series.Series'>
result:5 4
3 4
7 3
2 3
4 2
1 2
9 2
0 1
6 1
dtype: int64
|