2

So basically I have a list of strings say :

['cbad','hfig','qspr','uyxz'] 

I want to sort these strings in an alternate fashion without changing their relative position :

['abcd' ,'ihgf', 'pqrs', 'zyxu'] 

i.e. 'abcd' is sorted in ascending order, then 'ihgf' is sorted in 'descending order, then 'pqrs' is sorted in ascending and so on alternately.

So, instead of sorting these list of strings by looping through the list element wise, is there any other efficient way to do this in Python ? (keeping in mind that the list may contain a large number of elements).

Also, is it possible to do it in such that I can define a sort of custom order for sorting, like if I want every third element to be sorted in descending order. like this :

['abcd' ,'fghi', 'srqp', 'uxyz'] 
2
  • The most basic solution that comes to mind is to make a function for sorting which takes the string and a flag(0-ascending sort, 1-descending). Iterate through the list and vary the flag as per your need Commented Sep 12, 2017 at 3:37
  • @AbhishekAgarwal I stated that solution in my question, I wanted a more efficient or smaller way of doing it using list comprehension or something similar as stated in the accepted answer. Commented Sep 12, 2017 at 5:39

1 Answer 1

6

This one liner works:

mylist = ['cbad','hfig','qspr','uyxz'] ["".join(sorted(s, reverse=i%2)) for i,s in enumerate(mylist)] 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.