Python - 如果两个列表对象的名字大写,则彼此连接

Python - Join Two List Object Eachother If Their First Name Uppercase

是否可以对连续的大写单词进行分组?

例如我有一个这样的列表:

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

list =[['John'],['is'],['smart'],[','],['John'],['Kenneddy'],['is'],['smarter'],[','],['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)

您可以利用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())),
    [])