簡體   English   中英

如何從列表中創建字典,其中每個元素的計數是鍵,值是相應元素的列表?

[英]How to create a dictionary from a list where the count of each element is the key and values are the lists of the according element?

例如:

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

output 應該是:

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

其中 key = 1 是元素 1 的計數,而 value 是包含所有計數為 1 的元素的列表,依此類推。

以下代碼創建了三個字典,其中多次出現相同計數的情況以不同方式處理:

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)

Output:

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 :包含具有相應計數的元素列表列表

您可以嘗試將字典理解與過濾器或列表理解一起使用

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)})

或者

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

Output

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM