Joining side by side words from list in Python

  • A+
Category:Languages

Have a bunch of lists that are converted from a .txt file that have been read as a collection of strings that look like:

['New', 'Jersey', '1', '0', '1', '999'] ['West', 'North', 'Central', '1', '0', '100', '90'] 

These lists have differing numbers of side-by-side words (the first has 2 the second has 3, etc..)

I want to output a new list (then into a compiled dataframe) that joins the words together that are side-by-side like:

['New Jersey', '1', '0', '1', '999'] ['West North Central', '1', '0', '100', '90'] 

Which will make the new list (and dataframe) of the same length.

It's easy to just append(line.split()) into a new list for each string but can't figure out the if-statement and .join() needed to join all words and append each number separately.

 


Using itertools.groupby, you can group by str.isalpha, join strings conditionally, and then chain the results:

from itertools import chain, groupby  L = ['New', 'Jersey', '1', '0', '1', '999']  grouper = groupby(L, key=str.isalpha) joins = [[' '.join(v)] if alpha_flag else list(v) for alpha_flag, v in grouper] res = list(chain.from_iterable(joins))  print(res)  ['New Jersey', '1', '0', '1', '999'] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: