簡體   English   中英

Python:計算列表中列表元素的出現次數

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

我正在嘗試計算列表中元素出現的次數,如果這些元素也是列表。 順序也很重要。

[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

有沒有辦法做到這一點?

列表不可散列,但您可以使用元組作為解決方法:

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

您不能將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})

只需在某些等效類型上使用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})

列表的另一種實現

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

不要使用列表作為變量名。

如果您不想使用任何模塊,可以嘗試這種方法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM