Python:数组中的拆分列表 [英] Python: Split list in array

查看:376
本文介绍了Python:数组中的拆分列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从python开始,知道我知道什么都不知道。我想找到将列表分成列表列表的其他方式。示例列表:

Just beginning with python and know enough to know I know nothing. I would like to find alternative ways of splitting a list into a list of dicts. Example list:

data = ['**adjective:**', 'nice', 'kind', 'fine',
        '**noun:**', 'benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal', 
        '**adverb:**', 'well', 'nicely', 'fine', 'right', 'okay'] 

我可以得到:

[{'**adjective**': ('nice', 'kind', 'fine'),
 '**noun**': ('benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal'),
 '**adverb**': ('well', 'nicely', 'fine', 'right', 'okay')}] 


推荐答案

这可能是一样接近你所问的:

This might be as close at it gets to what you have asked:

d = collections.defaultdict(list)
for s in data:
    if s.endswith(":"):
        key = s[:-1]
    else:
        d[key].append(s)
print d
# defaultdict(<type 'list'>, 
#     {'adjective': ['nice', 'kind', 'fine'], 
#      'noun': ['benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal'], 
#      'adverb': ['well', 'nicely', 'fine', 'right', 'okay']})

编辑: - 由SilentGhost的答案启发:

Just for fun an alternative two-liner inspired by the answer by SilentGhost:

g = (list(v) for k, v in itertools.groupby(data, lambda x: x.endswith(':')))
d = dict((k[-1].rstrip(":"), v) for k, v in itertools.izip(g, g))

这篇关于Python:数组中的拆分列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆