Python - join two list objects if their name is exceeded

Is it possible to group Uppercased words that are consecutive?

For example, I have a list:

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

Output Required:

[['John'],['is'],['smart'],[','],['John','Kenneddy'],['is'],['smarter'],[','],['John','Fitzgerald','Kennedy'],['is'],['best']]
+4
source share
2 answers

You can use groupbyto group words starting with a letter:

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

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)
0
source

All Articles