Python | Combine only adjacent words in a list

Python Methods and Functions

Method # 1: Using comprehension list + * operator
This task can be accomplished using list comprehension, first by combining words and then combining numbers and then splitting only the numbers when concatenating to form the resulting string.

# Python3 demo code
# concatenate only adjacent words in a list
# list comprehension + operator & quot; * & quot;

  
# initializing list

test_list = [ 'Geeks' , '5' , ' for' , '9' , 'Geeks' , ' 2' , '5' ]

  
# print original list

print ( "The original list:" + str (test_list))

  
# using comprehension list + operator & quot; * & quot;
# concatenate only adjacent words in the list

res = ['' .join ([i for i in test_list if not i.isdigit ()]),

* [j for j in test_list if j.isdigit ()] ]

 
# print result

print ( "The joined adjacent word list (ignoring digits):" + str (res))

Exit:

The original list: ['Geeks',' 5 ',' for ',' 9 ',' Geeks', '2', '5']
The joined adj acent word list (ignoring digits): ['GeeksforGeeks', '5', '9', '2', '5']

Method # 2: Using itertools.chain.from_iterable () + groupby () + join ()
This task can also be accomplished with the groupby function, which groups the numbers together, and then the from_iterables function joins the list and characters together, joined by a join function.

# Python3 demo code
# join only adjacent words in the list
# itertools.chain.from_iterable () + groupby () + join ()

from itertools import chain, groupby

 
# initializes list

test_list = [ 'Geeks' , ' 5' , ' for' , 'Geeks' , '2' , '3' ]

  
# print the original list

print ( "The original list:" + str (test_list))

 
# using itertools.chain.from_iterable () + groupby () + join ()
# concatenate only adjacent words in the list

num_group = groupby (test_list, key = str .isalpha)

both_group = [ ['' .join (i)] if j else list (i)

for j, i in num_group ]

 

res = list (chain.from_iterable (both_group))

 
# print result

print ( "The joined adjacent word list (ignoring digits):"

+ str (res))

Exit:

The original list: ['Geeks', '5' , 'for', 'Geeks',' 2 ',' 3 ']
The joined adjacent word list (ignoring digits): [' Geeks', '5', 'forGeeks',' 2 ',' 3 ']





Get Solution for free from DataCamp guru