简体   繁体   English

Python:计算列表中列表元素的出现次数

[英]Python: Counting occurrences of List element within List

I'm trying to count the number of occurrences of elements within a list, if such elements are also lists.我正在尝试计算列表中元素出现的次数,如果这些元素也是列表。 The order is also important.顺序也很重要。

[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 }

One important factor is that ['a', 'b', 'c'] != ['c', 'b', 'a']一个重要的因素是['a', 'b', 'c'] != ['c', 'b', 'a']

I have tried:我试过:

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

Which both resulted in ['a', 'b', 'c'] = ['c', 'b', 'a'] , one thing i didn't want这两者都导致['a', 'b', 'c'] = ['c', 'b', 'a'] ,我不想要的一件事

I also tried:我也试过:

from collections import counter
print( Counter( lst ) )

Which only resulted in error;这只会导致错误; since lists can't be used as keys in dicts .因为lists不能用作dicts keys

Is there a way to do this?有没有办法做到这一点?

Lists are not hashable, but you can use tuples as a workaround:列表不可散列,但您可以使用元组作为解决方法:

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}

Output:输出:

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

Or, if you really want to use lists, you can create a custom class to mimic the functionality of a dictionary hashing lists:或者,如果你真的想使用列表,你可以创建一个自定义类来模拟字典哈希列表的功能:

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']])

Output:输出:

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

You can't have list as a key to the dict because dictionaries only allows immutable objects as it's key.您不能将list作为dict的键,因为字典只允许不可变对象作为键。 Hence you need to firstly convert your objects to tuple.因此,您需要首先将对象转换为元组。 Then you may use collection.Counter to get the count of each tuple as:然后你可以使用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})

just use collections.Counter on some equivalent type but hashable: the tuple :只需在某些等效类型上使用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)

result:结果:

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

Another implementation with lists列表的另一种实现

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))

and if you want an dictionary from that you can just change the last part to如果你想要一本字典,你可以把最后一部分改为

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

Don't Use list as variable name.不要使用列表作为变量名。

You can try this approach if you don't want to use any module :如果您不想使用任何模块,可以尝试这种方法:

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)

outoput:输出:

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

You can also use default dict:您还可以使用默认字典:

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())))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM