我有一個 Python 串列:
list_1 = [1, 2, 3, 11, 22, 33, 111, 222, 3333, 2222, 1111, 333]
我想回傳一個字典,其鍵是串列中專案的長度,值是具有與鍵相同長度的專案的串列。
示例輸出如下所示:
Dict_1 = {1 : [1,2,3],2:[11,22,33],3:[111,222,333]...}
uj5u.com熱心網友回復:
你可以這樣做:
from collections import defaultdict
lst = [1, 2, 3, 11, 22, 33, 111, 222, 3333, 2222, 1111, 333]
d = defaultdict(list)
for item in lst:
d[len(str(item))].append(item)
print(d)
uj5u.com熱心網友回復:
這是概率 更容易使用itertools groupby的功能來解決這個問題:
注意 - 它基于輸入串列是有序的假設,這意味著每個專案都是有序的。否則,它應該首先對其進行排序。感謝@SB 的評論/反饋
其余的格式化和放入輸出中作為練習。;-)(你現在可以試試 嗎?)
# L is your input list
from itertools import groupby
dc = dict()
for k, g in groupby(L, key=lambda x: len(str(x))):
print(k, list(g))
輸出:
1 [1, 2, 3]
2 [11, 22, 33]
3 [111, 222]
4 [3333, 2222, 1111]
3 [333]
uj5u.com熱心網友回復:
Dict_1 = {}
for i in list_1:
if len(i) not in Dict_1:
Dict_1[len(i)] = [i]
else:
Dict_1[len(i)].append(i)
print(Dict_1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/515887.html
上一篇:序列串列的子序列化
