2017-05-01 10 views
0

辞書のリスト、または各要素が等しいサイズのリストリストを持っているとします。 2要素→ [{1,2}, {3,4}, {4,6}, {1,2}]または[[1,2], [3,4], [4,6], [1,2]]リスト内の重複するリスト/指示値を確認する

重複を確認して繰り返し回数を確認するにはどうすればよいですか?

このようなものは動作しますが、私の場合は直接使用できません。

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)) 
関連する問題