如何从一个列表创建字典,其中每个元素的数量是键,值是相应元素的列表?

时间:2020-07-15 05:22:39

标签: python python-3.x

例如:

list = [1,2,2,3,3,3,4,4,4,4]

输出应为:

{1:[1],2:[2,2],3:[3,3,3],4:[4,4,4,4]}

其中key = 1是元素1的计数,值是包含所有计数为1的元素的列表,依此类推。

2 个答案:

答案 0 :(得分:0)

以下代码创建了三个字典,其中相同计数多次出现的情况得到了不同的处理:

l = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 44, 44, 44, 44]

d_replace = dict()
d_flat = dict()
d_nested = dict()
for item in set(l):
    elements = list(filter(lambda x: x == item, l))
    key = len(elements)
    d_replace[key] = elements
    d_flat.setdefault(key, list()).extend(elements)
    d_nested.setdefault(key, list()).append(elements)

print('Dictionary with replaced elements:\n', d_replace)
print('\nDictionary with a flat list of elements\n', d_flat)
print('\nDictionary with a nested lists of elements\n', d_nested)

输出:

Dictionary with replaced elements:
 {1: [1], 2: [2, 2], 3: [3, 3, 3], 4: [44, 44, 44, 44]}

Dictionary with a flat list of elements
 {1: [1], 2: [2, 2], 3: [3, 3, 3], 4: [4, 4, 4, 4, 44, 44, 44, 44]}

Dictionary with a nested lists of elements
 {1: [[1]], 2: [[2, 2]], 3: [[3, 3, 3]], 4: [[4, 4, 4, 4], [44, 44, 44, 44]]}
  • d_replace:相应的元素列表将被覆盖。
  • d_flat:仅包含一个具有相应计数的元素列表
  • d_nested:包含具有相应计数的元素列表的列表

答案 1 :(得分:0)

您可以尝试将dict理解与过滤器或列表理解一起使用

ls = [1,2,2,3,3,3,4,4,4,4]

print({ls.count(i): [el for el in ls if el == i] for i in set(ls)})

OR

print({ls.count(i): list(filter(lambda x: x == i, ls)) for i in set(ls)})

输出

{1: [1], 2: [2, 2], 3: [3, 3, 3], 4: [4, 4, 4, 4]}