Python 检查列表中是否存在重复的列表/dict值
如果我有一个字典列表或一个每个元素大小相等的列表,例如2个元素→ <代码>[{1,2},{3,4},{4,6},{1,2}]或Python 检查列表中是否存在重复的列表/dict值,python,list,python-3.x,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)] 最简单的方法是使用计数器,但必须转换为可散列(即不可变)类型: 这是假设顺序无关紧要,不过,您可以创建OrderedCounte
[[1,2],[3,4],[4,6],[1,2]
如何检查重复并记录重复次数
对于列表,类似这样的东西可以工作,但我不能在我的例子中直接使用set
recur1 = [[x, status.count(x)] for x in set(list1)]
最简单的方法是使用
计数器
,但必须转换为可散列(即不可变)类型:
这是假设顺序无关紧要,不过,您可以创建OrderedCounter
如果您有一个列表列表,则自然会选择元组
:
>>> 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})
最简单的方法是使用
计数器
,但必须转换为可散列(即不可变)类型:
这是假设顺序无关紧要,不过,您可以创建OrderedCounter
如果您有一个列表列表,则自然会选择元组
:
>>> 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})
您可以使用集合中的计数器:
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"
您可以使用集合中的计数器:
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"
您可以使用show show show should look the expected results这不是
dict
列表,这是set
列表。您可以使用show show show should look the expected results这不是dict
列表,这是set
列表。
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))