Method: Using join () + enumerate ()
+ generator expression + sorted()
This task can be achieved using a combination of the functions above. In this we are doing a sort using only% 2 items in the string list. The expansion of this operation to the entire list is done by a generator expression.
# Python3 code to demonstrate how it works # List of alternate sort strings # using join () + enumerate () + generator expression + sorted () # initialize the list test_list = [ ’cdab’ , ’gfeh’ , ’ kjil’ ] # print original list print ( "The original list:" + str (test_list)) # List of alternate sort strings # using join () + enumerate () + generator expression + sorted () res = ["". join ( sorted (j, reverse = i % 2 )) for i, j in enumerate (test_list)] # ne chat print ( "The String list after alternate sorting: " + str (res)) |
Output:
The original list: [’ cdab’, ’gfeh’,’ kjil’] The String list after alternate sorting: [’abcd’,’ hgfe’, ’ijkl’]
Python | Alternative sorting in a list of strings Python functions: Questions
Python | Alternative sorting in a list of strings String Variables: Questions