且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python:数组中的拆分列表

更新时间:2022-06-11 00:16:07

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

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