我有一个二维列表,我想通过使用列表理解返回最多的重复项。例如,我有下面的列表
a = [[10, 15, 17,],[20,21,27],[10,15,17],[21,27,28],[21,27,28],[5,10,15],[15,17,20]]
我希望我的结果是
b = [[10,15,17],[21,27,28]
计算重复次数的常见解决方案是collections.Counter:
from collections import Counter
a = [[10, 15, 17], [20, 21, 27], [10, 15, 17], [21, 27, 28], [21, 27, 28], [5, 10, 15], [15, 17, 20]]
# count duplicates
counts = Counter(map(tuple, a))
# find the maximum count (the values of counts are the duplicate count)
maximum_count = max(counts.values())
# filter and convert back to list
result = [list(e) for e, count in counts.items() if count == maximum_count]
print(result)
输出
[[10, 15, 17], [21, 27, 28]]
在您的情况下,特别是列表的元素是列表,您需要将它们转换为元组(以使它们可散列),然后只需过滤列表并保留最大计数的元素。
此处分成一行:
[ a[k]
for k in range(len(a))
if a.count( a[k] ) > 1
and k == a.index( a[k] ) ]
最简单的方法是找到每个元素的计数,并存储最大计数。然后,显示具有最大计数的所有元素(删除重复项)。
以下代码适合您:
a = [[10, 15, 17,],[20,21,27],[10,15,17],[21,27,28],[21,27,28],[5,10,15],[15,17,20]]
check=0
for i in a:
if a.count(i) > check:
check=a.count(i) #Check to see maximum count
b=[]
for i in a:
if a.count(i) == check: #Choosing elements with maximum count
if i not in b: #Eliminating duplicates
b.append(i)
print(b)
输出:
[[10, 15, 17], [21, 27, 28]]