python--- 统计列表中每个数据值出现的次数并组织成字典展示

目录

1. for 循环

2. for循环方法2:

3. 利用内置函数Counter

4. 利用函数


eg: l1 = ['yietong','yietong','kevin','oscar']
      结果:{'yietong':2,'kevin':1,'oscar':1}
    真实数据
        l1 = ['yietong','yietong','kevin','oscar','kevin','tony','kevin']

提供以下四种方法:

1. for 循环

建一个空字典, 循环打印列表,根据列表中元素出现的次数计数, 转换成字典格式.

l1 = ['yietong','yietong','kevin','oscar','kevin','tony','kevin']

dict = {}
for i in l1:
    if i not in dict:
        dict[i] = 1
    else:
        dict[i] += 1
print(dict)  # {'yietong': 2, 'kevin': 3, 'oscar': 1, 'tony': 1}

2. for循环方法2:

 先将列表转换成集合,在统计列表中元素出现的次数.

l1 = ['yietong','yietong','kevin','oscar','kevin','tony','kevin']


l = {}
for i in set(l1)
    l[i] = l1.count(i)
print(l)
# {'yietong': 2, 'tony': 1, 'kevin': 3, 'oscar': 1}

3. 利用内置函数Counter

引用模块,最简便快速的方式

l1 = ['yietong','yietong','kevin','oscar','kevin','tony','kevin']


from collections import Counter
l = Counter(l1)
print(l)  # Counter({'kevin': 3, 'yietong': 2, 'oscar': 1, 'tony': 1})

4. 利用函数

for循环时将列表数据类型转换成集合(字典格式会报错),统计元素出现次数.

执行函数,将结果作为返回值return出去

l1 = ['yietong','yietong','kevin','oscar','kevin','tony','kevin']


def list(l1):
    l = {}
    for i in set(l1):
        l[i] = l1.count(i)
    return l
print(list(l1))  # {'oscar': 1, 'yietong': 2, 'kevin': 3, 'tony': 1}

 此方法是基于方法2之上的进阶版.

你可能感兴趣的:(python基础,大数据)