2017-05-01 87 views
0

如果我有一個字典列表或每個元素大小相同的列表列表,例如, 2個元素→ [{1,2}, {3,4}, {4,6}, {1,2}][[1,2], [3,4], [4,6], [1,2]]檢查列表中的重複列表/字典值

如何檢查重複並保持重複次數?

對於列表,這樣的東西會工作,但我不能直接在我的情況下使用set。

recur1 = [[x, status.count(x)] for x in set(list1)] 
+0

你可以使用['計數器'](https://docs.python.org/3/library/collections.html#collections.Counter) –

+1

顯示應該如何看待預期結果 – RomanPerekhrest

+2

這不是'dict'列表,這是'set '。 –

回答

2

最簡單的方法是使用一個Counter,但你必須轉換爲可哈希(即不變的)類型:

>>> from collections import Counter 
>>> objs = [{1,2}, {3,4}, {4,6}, {1,2}] 
>>> counts = Counter(objs) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/Users/juan/anaconda3/lib/python3.5/collections/__init__.py", line 530, in __init__ 
    self.update(*args, **kwds) 
    File "/Users/juan/anaconda3/lib/python3.5/collections/__init__.py", line 617, in update 
    _count_elements(self, iterable) 
TypeError: unhashable type: 'set' 

因此,對於一組,自然選擇是frozenset

>>> counts = Counter(frozenset(s) for s in objs) 
>>> counts 
Counter({frozenset({1, 2}): 2, frozenset({4, 6}): 1, frozenset({3, 4}): 1}) 
>>> 

這是假設順序並不重要,但是,你可以創建一個OrderedCounter almost trivially...

相反,如果你有一個列表的列表,一個tuple將是自然的選擇:

>>> objs = [[1,2], [3,4], [4,6], [1,2]] 
>>> counts = Counter(tuple(l) for l in objs) 
>>> counts 
Counter({(1, 2): 2, (3, 4): 1, (4, 6): 1}) 
0

您可以使用計數器從集合:

from collections import Counter 

the_list = [[1,2], [3,4], [4,6], [1,2]] 
new_list = map(tuple, the_list) 
the_dict = Counter(new_list) 

final_list = [a for a, b in the_dict.items() if b > 1] 
#the number of duplicates: 
print len(final_list) 
#the duplicates themselves: 
print final_list 

if len(final_list) > 0: 
    print "Duplicates exist in the list" 
    print "They are: " 
    for i in final_list: 
     print i 

else: 
    print "No duplicates" 
0
ll = [[1,2], [3,4], [4,6], [1,2]] 

# Step1 Using a dictionary. 

counterDict = {} 
for l in ll: 
    key = tuple(l) # list can not be used as a dictionary key. 
    if key not in counterDict: 
    counterDict[key] = 0 
    counterDict[key] += 1 
print(counterDict) 


# Step2 collections.Counter() 
import collections 
c = collections.Counter([ tuple(l) for l in ll]) 
print(c) 


# Step3 list.count() 
for l in ll: 
    print(l , ll.count(l))