【问题标题】:How to make a counting function that returns the number of elements in a list如何制作一个返回列表中元素数量的计数函数
【发布时间】:2019-01-29 13:17:35
【问题描述】:

我正在尝试创建一个对列表中的元素进行计数的函数,为此我正在使用 Python。该程序应该接受像[a, a, a, b, b, c, c, c, c] 这样的列表并返回一个值[3, 2, 4],但我遇到了麻烦。我该怎么办?

【问题讨论】:

  • print( [lst.count(i) for i in set(lst)] ) ?
  • 你怎么知道3属于a,2属于b,4属于c?
  • 使用collections.Counter
  • 给定[a, a, a, b, b, a]的函数应该做什么?返回[4, 2][3, 2, 1]?

标签: python


【解决方案1】:

如果给定['a', 'a', 'a', 'b', 'b', 'a'] 你想要[3, 2, 1]

import itertools
result = [len(list(iterable)) for _, iterable in itertools.groupby(my_list)]

【讨论】:

  • 只是一个补充:[(k, sum(1 for _ in v)) for k, v in itertools.groupby(my_list)] 是一个如何获取计数元素映射的示例。
【解决方案2】:

使用 dict 并用它做一个计数器。

a,b,c = "a","b","c"
inp = [a,a,a,b,b,c,c,c,c]
dic = {}
for i in inp:
    if i in dic:
        dic[i]+=1
    else:
        dic[i] = 1
print(dic)  #Dict with input values and count of them
print(dic.values())  #Count of values in the dict

请记住,这会改变输入列表的顺序。 要保持订单不变,请使用 Collections 库中的 OrderedDict 方法。

from collections import OrderedDict
a,b,c = "a","b","c"
inp = [a,a,a,b,b,c,c,c,c]
dic = OrderedDict()
for i in inp:
    if i in dic:
        dic[i]+=1
    else:
        dic[i] = 1
print(dic)
print(dic.values())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 2016-06-21
    • 2021-07-24
    • 1970-01-01
    • 2023-03-08
    • 2022-01-15
    • 2021-10-13
    相关资源
    最近更新 更多