您可以简单地使用计数器,如下所示 [Counter(l) for l in lst_of_lsts]
:
代码 1
from collections import Counter
lst_of_lsts = [
["e", "d", "c", "b", "a", "c", "d", "b"],
["e", "b", "c", "a", "b", "e", "c"],
["a", "b", "a", "d", "b", "a", "a"],
["a", "b", "c", "d", "e", "c", "d"],
["e", "d", "c", "b", "a"]
]
counters = [Counter(l) for l in lst_of_lsts]
res = [counter.most_common(1)[0] for counter in counters]
print(counters)
print(res)
印刷
[Counter({'d': 2, 'c': 2, 'b': 2, 'e': 1, 'a': 1}), Counter({'e': 2, 'b': 2, 'c': 2, 'a': 1}), Counter({'a': 4, 'b': 2, 'd': 1}), Counter({'c': 2, 'd': 2, 'a': 1, 'b': 1, 'e': 1}), Counter({'e': 1, 'd': 1, 'c': 1, 'b': 1, 'a': 1})]
[('d', 2), ('e', 2), ('a', 4), ('c', 2), ('e', 1)]
代码 2
from collections import Counter
lst_of_lsts = [
["e", "d", "c", "b", "a", "c", "d", "b"],
["e", "b", "c", "a", "b", "e", "c"],
["a", "b", "a", "d", "b", "a", "a"],
["a", "b", "c", "d", "e", "c", "d"],
["e", "d", "c", "b", "a"]
]
counter = Counter([tuple(sorted(l)) for l in lst_of_lsts])
print(counter.most_common(1)[0])
印刷
(('a', 'b', 'b', 'c', 'c', 'd', 'd', 'e'), 1)
代码 3
from collections import Counter
lst_of_lsts = [
["e", "d", "c", "b", "a", "c", "d", "b"],
["e", "b", "c", "a", "b", "e", "c"],
["a", "b", "a", "d", "b", "a", "a"],
["a", "b", "c", "d", "e", "c", "d"],
["e", "d", "c", "b", "a"]
]
counter = Counter([tuple(sorted(set(l))) for l in lst_of_lsts])
print(counter)
print(counter.most_common(1)[0])
印刷
Counter({('a', 'b', 'c', 'd', 'e'): 3, ('a', 'b', 'c', 'e'): 1, ('a', 'b', 'd'): 1})
(('a', 'b', 'c', 'd', 'e'), 3)
代码4:
import string
from collections import Counter
from itertools import combinations
lst = string.ascii_lowercase[0:6]
combinations_of_5 = tuple(combinations(lst, 5))
# print(combinations_of_5)
lst_of_lsts = [
["e", "d", "c", "b", "a", "c", "d", "b"],
["e", "b", "c", "a", "b", "e", "c"],
["a", "b", "a", "d", "b", "a", "a"],
["a", "b", "c", "d", "e", "c", "d"],
["e", "d", "c", "b", "a"]
]
res = Counter([tuple(sorted(l)) for l in lst_of_lsts if len(l) == len(set(l)) and len(l) == 5])
print(res)
印刷
Counter({('a', 'b', 'c', 'd', 'e'): 1})