加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

pythonic将列表列表拆分为长度键控字典的方法?

发布时间:2020-12-20 12:12:42 所属栏目:Python 来源:网络整理
导读:xs = [ [1,2,3,4],[5,6,7,8],[9,1],[2,3],[0],8,5,[6,[1,9,9]]""" expected output: xs_dict = { 1: [[0]] 2: [[2,4]] 4: [[1,1]] 6: [[5,9]] }""" 我可以这样做,例如,通过 xs_dict = {}for x in xs: aux = xs_dict.get(len(x),[]) aux.append(x) xs_dict[le
xs = [
        [1,2,3,4],[5,6,7,8],[9,1],[2,3],[0],8,5,[6,[1,9,9]
]

""" expected output:

    xs_dict = {
        1: [[0]]
        2: [[2,4]]
        4: [[1,1]]
        6: [[5,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()替换groupby(sorted(…),…),它可以处理未排序的输入.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读