python列表分割,Python:数组中的拆分列表

这篇博客介绍了如何使用Python将带有特定标签的列表转换为字典,便于数据组织。通过defaultdict和itertools.groupby,可以将带有'adjective:', 'noun:'和'adverb:'标签的元素分别归类到对应的字典键下,形成一个包含多个键值对的字典。
摘要由CSDN通过智能技术生成

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']

I would be able to get:

[{'**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(,

# {'adjective': ['nice', 'kind', 'fine'],

# 'noun': ['benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal'],

# 'adverb': ['well', 'nicely', 'fine', 'right', 'okay']})

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值