【问题标题】:Occurrence of an element in list列表中某个元素的出现
【发布时间】:2021-08-27 14:37:24
【问题描述】:

我想获取给定list 中每个值的频率。

fruits = ["apple", "banana", "cherry", "apple", "banana"]
counts = [fruits.count(x) for x in fruits]
print(counts)
>>> [2, 2, 1, 2, 2] # "apple", "banana", "cherry", "apple", "banana"

期望的输出

>>> [2, 2, 1] # "apple", "banana", "cherry"

其次;执行此操作的计算效率最高的方式可能是什么?

【问题讨论】:

  • 抱歉标题的措辞。我可能需要尽快改写它
  • 试试看Counter
  • 哦,好的,我会继续尝试有效的解决方案。然而,我有兴趣在相当大的范围内这样做。因此希望使用 primitive Python 代码来加快速度。

标签: python python-3.x list


【解决方案1】:

使用collections.Counter

from collections import Counter

[*Counter(fruits).values()]
# [2, 2, 1]

这会在一次迭代中收集所有计数。

【讨论】:

    【解决方案2】:

    您可以创建一个set(fruits) 来删除重复项,然后计算水果列表中的元素:

    fruits = ["apple", "banana", "cherry", "apple", "banana"]
    set_fruits = set(fruits)
    counts = [fruits.count(x) for x in set_fruits]
    print(counts)
    

    【讨论】:

    • fruits.count(x) 不是个好主意,你是在一次又一次地遍历列表。
    【解决方案3】:

    只需使用字典并计算频率。

    fruits = ["apple", "banana", "cherry", "apple", "banana"]
    counter_map = {}
    
    for each_fruit in fruits:
        if each_fruit in counter_map:
            counter_map[each_fruit] += 1
        else:
            counter_map[each_fruit] = 1
            
    print(list(counter_map.values())) #[2, 2, 1]
    

    【讨论】:

    • 你彻底改造了collections.Counter
    • 我理解你的双关语,但我有时觉得如果不从基本的事情做起,越过黑匣子接触新手可能不会有太大的好处。我可能错了!
    【解决方案4】:

    使用字典统计频率

    fruits = ["apple", "banana", "cherry", "apple", "banana"]
    freq = {}
    for fruit in fruits:
        freq[fruit] = freq.get(fruit,0) + 1
    print(list(freq.values()))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多