Python – 如果他们的名字大写,则加入两个列表对象
作者:互联网
是否可以对连续的大写单词进行分组?
例如,我有一个这样的列表:
lst =[['John'],['is'],['smart'],[','],['John'],['Kenneddy'],['is'],['smarter'],[','],['John'],['Fitzgerald'],['Kennedy'],['is'],['best']]
期望的输出:
[['John'],['is'],['smart'],[','],['John','Kenneddy'],['is'],['smarter'],[','],['John','Fitzgerald','Kennedy'],['is'],['best']]
解决方法:
您可以使用groupby
通过开头的字母对单词进行分组:
from itertools import groupby
d = [['John'],['is'],['smart'],[','],['John'],['Kenneddy'],['is'],[','],['John'],['Fitzgerald'],['Kennedy'],['is'],['best']]
sum(([[x[0] for x in g]] if k else list(g)
for k, g in groupby(d, key=lambda x: x[0][0].isupper())),
[])
标签:python,list,capitalization 来源: https://codeday.me/bug/20190608/1200527.html