python列表按第一个字符分组 [英] python list group by first character

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

问题描述

list1=['hello','hope','hate','hack','bit','basket','code','come','chess']

我需要的是:

list2=[['hello','hope','hate','hack'],['bit','basket'],['code','come','chess']]

如果第一个字符相同且属于同一组,则将其列出.

If the first character is the same and is the same group, then sublist it.

我该如何解决?

推荐答案

您可以使用 :

>>> from itertools import groupby
>>> list1 = ['hello','hope','hate','hack','bit','basket','code','come','chess']
>>> [list(g) for k, g in groupby(list1, key=lambda x: x[0])]
[['hello', 'hope', 'hate', 'hack'], ['bit', 'basket'], ['code', 'come', 'chess']]

这篇关于python列表按第一个字符分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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