Python连接两个列表对象,如果它们的名字是大写的

2024-04-26 17:53:45 发布

您现在位置: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']]

Tags: 列表issmartjohn单词best大写lst
2条回答

list=['John'],['is'],['smart'],['John'],['Kenneddy'],['is'],['smart'],[','],['John'],['Fitzgerald'],['Kennedy'],['is'],['best']]

  upperlist=[]
   tmp = 0
   for l in list:
        if l[0][0].isupper():
         if tmp != 0 and list[tmp-1] != ",":
            u =list[tmp-1]+l
            print(u)
            if u[0] == ',':
              if l not in upperlist:
               upperlist.append(l)
            else:

                  upperlist.append(u)
         else:

              upperlist.append(l)
        else:

            upperlist.append(l)
        tmp = tmp+1

print(upperlist)

您可以利用^{}按起始字母对单词进行分组:

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())),
    [])

相关问题 更多 >