我有一个列表,其中包含已填充的不同详细信息:
[['sku','3','batchid',4], ['sku','9','batchid',5], ['sku','3','batchid',5], ['sku','3','batchid',5]]
我需要在列表列表中找到4个元素的出现,并显示在列表列表中出现多个元素的元素。任何指导都将不胜感激。
预期产出:
{"3":[['sku','9','batchid',5],['sku','3','batchid',5],['sku','3','batchid',5]],
"1":[['sku','3','batchid',5]['sku','3','batchid',5]]}
答案 0 :(得分:3)
计算第4个元素
from collections import Counter
from operator import itemgetter
print(Counter(map(itemgetter(3), lst)))
# Counter({5: 3, 4: 1}) and it will act as a normal dictionary
或获取最常见的列表
from operator import itemgetter
print(max(lst, key=lst.count)) # ['sku', '3', 'batchid', 5]
<强>更新强>
如果您的预期输出是
{"3":[['sku','9','batchid',5],['sku','3','batchid',5],['sku','3','batchid',5]],
"1":[['sku','3','batchid',4]]}
然后是解决方案
from itertools import groupby
lst.sort(key=lambda x: x[3])
d = {}
for x, y in groupby(lst, key=lambda x: x[3]):
y = list(y)
d[len(y)] = y
print(d)
输出
{1: [['sku', '3', 'batchid', 4]],
3: [['sku', '9', 'batchid', 5],
['sku', '3', 'batchid', 5],
['sku', '3', 'batchid', 5]]}
如果多个元素具有相同的出现次数:
from itertools import groupby
from collections import defaultdict
lst.sort(key=lambda x: x[3])
d = defaultdict(list)
for x, y in groupby(lst, key=lambda x: x[3]):
y = list(y)
d[len(y)].extend(y)
print(d)