Change language

Python | Split a list of strings into sublists by length

| | |

Examples :

  Input:  [’The’,’ art’, ’of’,’ programming’]  Output:  [[’of’], [’ The’, ’art’], [’ programming’]]  Input:  [’Welcome’,’ to’, ’pythonengineering’]  Output:  [[’to’], [’ Welcome’], [’pythonengineering’]] 

Approach # 1: Python is naive

The naive approach for the above method uses a dictionary and a for loop to traverse the list. At each iteration, it is checked whether the item’s length is in the list or not. If not, it adds the length of the element and the element as a key: value pair, otherwise the element is simply added to the sublist of values. Finally, we list all the dict values ​​and return it.

# Python3 program for splitting a list of strings
# in sublists based on line length

  

def divideList (lst):

dct = {}

  

for element in lst:

if len (element) not   in dct:

dct [ len (element)] = [element]

elif len (element) in dct:

dct [ len (element)] + = [element]

  

  res = []

for  key in sorted (dct):

res.append (dct [key])

 

return res

 
# Code drivers

lst = [ ’The’ , ’ art’ , ’ of’ , ’programming’ ]

print (divideList (lst))

Exit:

 [[ ’of’], [’ The’, ’art’], [’ programming’]] 

Approach # 2: defaultdict () from collections module

This method takes defaultdict and stores it in the & # 39; group_by_len & # 39; variable. Using a for loop, we store the length of the string as a key and the string with the length of the key as the value. Finally, we list all the group_by_len values ​​and return it.

# Python3 program for splitting a list of strings
# in sublists based on line length

from collections import defaultdict

 

def divideList (lst):

group_by_len = defaultdict ( list )

for ele in lst:

group_by_len [ len (ele)]. append (ele)

 

res = [ ]

for key in sorted (group_by_len):

res.append (group_by_len [key])

 

return res

 
# Driver code

lst = [ ’ The’ , ’art’ , ’ of’ , ’programming’ ]

print (divideList (lst))

Exit:

 [[’of’], [’ The’, ’art’], [’ programming’]] 

Approach # 3 : groupby () from itertools

The most efficient and simpler way to solve this problem is to use groupby () from the itertools module. This is a one line string where we use two variables & # 39; l & # 39; (for length) and & # 39; g & # 39; (group of lines) to go through & # 39; lst & # 39;, grouped by length and finally returning all groups packed into a list.

# Python3 program to split a list of lines
# into sublists based on line length

from itertools import groupby

 

def divideList (lst):

res = dict ((l, list (g)) for l, g in groupby (lst, key = len ))

 

  # Sort by key

res = sorted (res.items (), key = lambda kv: (kv [ 0 ], kv [ 1 ]))

 

# Deleting key from the list of tuples

return [ el [ 1 < / code> :] for el in ( tuple (x) for x in res)]

 
# Driver code

lst = [ ’The’ , ’art’ , ’of’ , ’ programming’ ]

print (divideList (lst))

Exit:

 [([’of’],), ([’ The’, ’art’], ), ([’programming’] ,)] 

Python | Split a list of strings into sublists by length Python functions: Questions

Python | Split a list of strings into sublists by length split: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method