检查列表中的重复列表/字典值

时间:2017-05-01 22:35:48

标签: python list python-3.x

如果我有一个字典列表或列表列表,其中每个元素的大小相等,例如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)]

3 个答案:

答案 0 :(得分: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})

答案 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"

答案 2 :(得分: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))