【问题标题】:Counting repeated strings in a list and printing计算列表中重复的字符串并打印
【发布时间】:2018-07-17 11:21:00
【问题描述】:

我有一个包含许多字符串的列表。有些字符串是重复的,所以我想计算它们重复了多少次。对于单数字符串,我只打印它,对于重复字符串,我想打印它的重复数。代码如下:

for string in list:
    if list.count(string) > 1:
    print(string+" appeared: ")
    print(list.count(string))
elif list.count(string) == 1:
    print(string)

但是它有一些问题,因为它正在打印重复字符串的所有实例。例如,如果列表中有两个“hello”字符串,它将打印hello appeared 2 两次。那么有没有办法跳过检查重复字符串的所有实例?感谢帮助。

【问题讨论】:

  • 为此使用collections.Counter
  • 旁注:永远不要在内置变量之后命名变量。使用lst 而不是list

标签: python list counter


【解决方案1】:

list.count 在循环中很昂贵。它将解析每个单词的整个列表。那是 O(n2) 复杂度。您可以遍历一组单词,但这是 O(m*n) 复杂度,仍然不是很好。

相反,您可以使用collections.Counter 解析您的列表一次。然后迭代您的字典键值对。这将具有 O(m+n) 复杂度。

lst = ['hello', 'test', 'this', 'is', 'a', 'test', 'hope', 'this', 'works']

from collections import Counter

c = Counter(lst)

for word, count in c.items():
    if count == 1:
        print(word)
    else:
        print(f'{word} appeared: {count}')

hello
test appeared: 2
this appeared: 2
is
a
hope
works

【讨论】:

    【解决方案2】:

    使用set

    例如:

    for string in set(list):
        if list.count(string) > 1:
            print(string+" appeared: ")
            print(list.count(string))
        elif list.count(string) == 1:
            print(string)
    

    【讨论】:

      【解决方案3】:

      使用Counter

      创建:

      In [166]: import collections
      
      In [169]: d = collections.Counter(['hello', 'world', 'hello'])
      

      显示:

      In [170]: for word, freq in d.items():
           ...:     if freq > 1:
           ...:         print('{0} appeared {1} times'.format(word, freq))
           ...:     else:
           ...:         print(word)
           ...:
      hello appeared 2 times
      world
      

      【讨论】:

        【解决方案4】:

        你可以像这样使用python的collections.counter -

        import collections
        result = dict(collections.Counter(list))
        

        另一种手动执行此操作的方法是:

        result = {k, 0 for k in set(list)}
        for item in list:
            result[item] += 1
        

        此外,您不应将列表命名为 list 作为其 python 的内置类型。现在这两种方法都会给你像 -

        {"a": 3, "b": 1, "c": 4, "d": 1}
        

        keys 是列表中的唯一值,而值是键在列表中出现的次数

        【讨论】:

          猜你喜欢
          • 2013-10-21
          • 1970-01-01
          • 2018-11-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多