【问题标题】:Python: Counting occurrences of List element within ListPython:计算列表中列表元素的出现次数
【发布时间】:2018-01-01 20:45:56
【问题描述】:

我正在尝试计算列表中元素的出现次数,如果这些元素也是列表的话。顺序也很重要。

[PSEUDOCODE]

lst = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['a', 'b', 'c'], ['c', 'b', 'a'] ]
print( count(lst) )


> { ['a', 'b', 'c'] : 2, ['d', 'e', 'f']: 1, ['c', 'b', 'a']: 1 }

一个重要的因素是['a', 'b', 'c'] != ['c', 'b', 'a']

我试过了:

from collections import counter
print( Counter([tuple(x) for x in lst]) )
print( [[x, list.count(x)] for x in set(lst)] )

两者都导致['a', 'b', 'c'] = ['c', 'b', 'a'],我不想要的一件事

我也试过了:

from collections import counter
print( Counter( lst ) )

这只会导致错误;因为lists 不能用作dicts 中的keys

有没有办法做到这一点?

【问题讨论】:

  • 那么到目前为止你尝试过什么?
  • tuple(['a', 'b', 'c']) == tuple(['c', 'b', 'a']) 给我False
  • 由于“列表不能用作字典中的键”,因此您想要的输出是不可能的;你想要什么?

标签: python list count


【解决方案1】:

您不能将list 作为dict 的键,因为字典只允许不可变对象作为键。因此,您需要首先将您的对象转换为元组。然后您可以使用collection.Counter 来获取每个元组的计数:

>>> from collections import Counter
>>> my_list = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['a', 'b', 'c'], ['c', 'b', 'a'] ]

#            v to type-cast each sub-list to tuple
>>> Counter(tuple(item) for item in my_list)
Counter({('a', 'b', 'c'): 2, ('d', 'e', 'f'): 1, ('c', 'b', 'a'): 1})

【讨论】:

    【解决方案2】:

    只需在一些等效类型上使用collections.Counter,但可散列:tuple

    import collections
    
    lst = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['a', 'b', 'c'], ['c', 'b', 'a'] ]
    
    c = collections.Counter(tuple(x) for x in lst)
    
    print(c)
    

    结果:

    Counter({('a', 'b', 'c'): 2, ('d', 'e', 'f'): 1, ('c', 'b', 'a'): 1})
    

    【讨论】:

      【解决方案3】:

      列表不可散列,但您可以使用元组作为解决方法:

      l = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['a', 'b', 'c'], ['c', 'b', 'a'] ]
      new_l = list(map(tuple, l))
      final_l = {a:new_l.count(a) for a in new_l}
      

      输出:

      {('a', 'b', 'c'): 2, ('d', 'e', 'f'): 1, ('c', 'b', 'a'): 1}
      

      或者,如果你真的想使用列表,你可以创建一个自定义类来模仿字典哈希列表的功能:

      class List_Count:
          def __init__(self, data):
             new_data = list(map(tuple, data))
             self.__data = {i:new_data.count(i) for i in new_data}
          def __getitem__(self, val):
             newval = [b for a, b in self.__data.items() if list(a) == val]
             if not newval:
                raise KeyError("{} not found".format(val))
             return newval[0]
          def __repr__(self):
             return "{"+"{}".format(', '.join("{}:{}".format(list(a), b) for a, b in self.__data.items()))+"}"
      
      l = List_Count([ ['a', 'b', 'c'], ['d', 'e', 'f'], ['a', 'b', 'c'], ['c', 'b', 'a'] ])
      print(l)
      print(l[['a', 'b', 'c']])
      

      输出:

      {['a', 'b', 'c']:2, ['d', 'e', 'f']:1, ['c', 'b', 'a']:1}
      2
      

      【讨论】:

      • 元组变通办法非常适合获得几乎单行的解决方案!
      【解决方案4】:

      另一个列表实现

      l1 = [["a", "b", "c"], ["b", "c", "d"], ["a", "b", "c"], ["c", "b", "a"]]
      
      def unique(l1):
          l2 = []
          for element in l1:
              if element not in l2:
                  l2.append(element)
          return l2
      
      l2 = unique(l1)
      for element in l2:
          print(element, l1.count(element))
      

      如果你想要一本字典,你可以把最后一部分改成

      output = {element:l1.count(element) for element in unique(l1)}
      

      【讨论】:

        【解决方案5】:

        不要使用列表作为变量名。

        如果您不想使用任何模块,可以尝试这种方法:

        list_1 = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['a', 'b', 'c'], ['c', 'b', 'a'] ]
        
        track={}
        
        for i in list_1:
            if tuple(i) not in track:
                track[tuple(i)]=1
            else:
                track[tuple(i)]+=1
        
        print(track)
        

        输出:

        {('a', 'b', 'c'): 2, ('d', 'e', 'f'): 1, ('c', 'b', 'a'): 1}
        

        你也可以使用默认字典:

        list_1 = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['a', 'b', 'c'], ['c', 'b', 'a'] ]
        
        track={}
        
        import collections
        d=collections.defaultdict(list)
        
        for j,i in enumerate(list_1):
            d[tuple(i)].append(j)
        
        print(list(map(lambda x:{x:len(d[x])},d.keys())))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-06-09
          • 2011-08-10
          • 2018-11-20
          • 2012-08-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多