3

I want to sort each string in a list of string to be in alphabetical order.

For example,

l1 = ["bba", "yxx", "abc"]

I want to sort it to be

l1 = ["abb", "xxy", "abc"]

I can do it in a for loop but wonder if this is a more pythonic way using python list comprehension. Thanks :D

1
  • ["".join(sorted(i)) for i in l1] Commented Feb 15, 2015 at 8:16

3 Answers 3

4

Using list comprehension and str.join:

>>> l1 = ["bba", "yxx", "abc"]
>>> [''.join(sorted(s)) for s in l1]
['abb', 'xxy', 'abc']
Sign up to request clarification or add additional context in comments.

Comments

2

by List compression with sorted method and string join method

>>> l1 = ["bba", "yxx", "abc"]
>>> [''.join(sorted(i)) for i in l1]
['abb', 'xxy', 'abc']
>>> 

by lambda

>>> l1
['bba', 'yxx', 'abc']
>>> map(lambda x:"".join(sorted(x)),l1)
['abb', 'xxy', 'abc']

For Python beginner

  1. Iterate every item of list l1 by for loop.
  2. Use sorted() method to sort item and return list.
  3. Use join() method to create string from the list.
  4. Use append() list method to add sored item to new list l2.
  5. print l2

e.g.

>>> l1
['bba', 'yxx', 'abc']
>>> l2 = []
>>> for i in l1:
...    a = sorted(i)
...    b = "".join(a)
...    l2.append(b)
... 
>>> l2
['abb', 'xxy', 'abc']

1 Comment

the lambda one needs to be converted in to a list if we want to be fair and compare times.
-1

Just use the sorted built-in function.

l1 = ["bba", "yxx", "abc"]
print [''.join(sorted(i)) for i in l1]

Another way of using list comprehensions (if your strings have a fixed length of 3) would be:

print ['{0}{1}{2}'.format(*sorted(i)) for i in l1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.