ksm*_*wee 2 python dictionary split list
刚开始使用python并且知道足够知道我什么都不知道.我想找到将列表拆分为dicts列表的替代方法.示例列表:
data = ['**adjective:**', 'nice', 'kind', 'fine',
'**noun:**', 'benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal',
'**adverb:**', 'well', 'nicely', 'fine', 'right', 'okay']
Run Code Online (Sandbox Code Playgroud)
我能得到:
[{'**adjective**': ('nice', 'kind', 'fine'),
'**noun**': ('benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal'),
'**adverb**': ('well', 'nicely', 'fine', 'right', 'okay')}]
Run Code Online (Sandbox Code Playgroud)
Sve*_*ach 10
这可能与您提出的要求非常接近:
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']})
Run Code Online (Sandbox Code Playgroud)
编辑:只是为了一个有趣的替代双线,灵感来自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))
Run Code Online (Sandbox Code Playgroud)
>>> data = ['adjective:', 'nice', 'kind', 'fine', 'noun:', 'benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal', 'adverb:', 'well', 'nicely', 'fine', 'right', 'okay']
>>> from itertools import groupby
>>> dic = {}
>>> for i, j in groupby(data, key=lambda x: x.endswith(':')):
if i:
key = next(j).rstrip(':')
continue
dic[key] = list(j)
>>> dic
{'adjective': ['nice', 'kind', 'fine'], 'noun': ['benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal'], 'adverb': ['well', 'nicely', 'fine', 'right', 'okay']}
Run Code Online (Sandbox Code Playgroud)