Python:计数字符串频率列表类型

2024-04-20 03:42:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用python来计算list的频率,而不使用任何集合,只使用我自己的python基本函数。 我的代码是:

my_list = ['a', 'b','a', 'a','b','b', 'a','a','c']

def counting(): 
#Please help

打印输出应该是

a: 5
b: 3
c: 1

请帮忙谢谢。你知道吗


Tags: 函数代码mydefhelplist频率please
2条回答

创建一个字典来保存结果并检查键是否存在,否则将值设置为1(第一次出现)。你知道吗

my_list = ['a', 'b','a', 'a','b','b', 'a','a','c']

def counting(my_list):
  counted = {}
  for item in my_list:
    if item in counted:
      counted[item] += 1
    else:
      counted[item] = 1

  return counted

print(counting(my_list))

使用count,一个内置的list函数。你知道吗

def counting(my_list):
      return { x:my_list.count(x) for x in my_list }

就叫它:

>>> counting(my_list)
=> {'a': 5, 'b': 3, 'c': 1}

#print it as per requirement
>>> for k,v in counting(my_list).items(): 
        print(k,':',v) 

a : 5
b : 3
c : 1

#驱动程序值:

IN : my_list = ['a', 'b','a', 'a','b','b', 'a','a','c']

相关问题 更多 >