簡體   English   中英

pythonic將列表列表拆分為長度鍵控字典的方法?

[英]pythonic way of splitting a list of lists into a length-keyed dictionary?

xs = [
        [1,2,3,4],
        [5,6,7,8],
        [9,0,0,1],
        [2,3],
        [0],
        [5,8,3,2,5,1],
        [6,4],
        [1,6,9,9,2,9]
]

""" expected output:

    xs_dict = {
        1: [[0]]
        2: [[2,3],[6,4]]
        4: [[1,2,3,4],[5,6,7,8],[9,0,0,1]]
        6: [[5,8,3,2,5,1],[1,6,9,9,2,9]]
    }
"""

我可以這樣做,例如,通過

xs_dict = {}
for x in xs:
    aux = xs_dict.get(len(x),[])
    aux.append(x)
    xs_dict[len(x)] = aux

print(xs_dict)

但我不禁覺得應該有更多的pythonic方法來實現這一目標。

它是什么?

from itertools import groupby

xs_dict = {
    key: list(value)
    for (key, value) in groupby(sorted(xs, key=len), len)
}

正如下面的評論中所討論的那樣,輸入的必要分類是一個不必要的代價。 對於大輸入,這將使這種算法的速度超過必要的速度。 考慮使用@ hiroprotagonist的解決方案,而不是再或者更換groupby(sorted(…), …)groupby()它可以處理未排序的輸入。

你可以使用defaultdict

from collections import defaultdict

xs_dict = defaultdict(list)
for item in xs:
    xs_dict[len(item)].append(item)

python dict也有一個很好的方法叫做setdefault (這樣你不需要導入任何東西):

xs_dict = {}
for item in xs:
    xs_dict.setdefault(len(item), []).append(item)
import pprint
from collections import defaultdict
from itertools import groupby

xs = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 0, 0, 1],
    [2, 3],
    [0],
    [5, 8, 3, 2, 5, 1],
    [6, 4],
    [1, 6, 9, 9, 2, 9]
]

data = defaultdict(list)

for result, group in groupby(sorted(xs, key=len), len):
    for item in group:
        data[result].append(item)

pprint.pprint(dict(data))

給我

{1: [[0]],
 2: [[2, 3], [6, 4]],
 4: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 0, 1]],
 6: [[5, 8, 3, 2, 5, 1], [1, 6, 9, 9, 2, 9]]}

1班輪:

res = {len(s): [d for d in xs if len(d) == len(s)] for s in xs}

暫無
暫無

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

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