1

i was wondering if there was any simple way around sorting tuples in lists in python, for instance if i have a list:

list01 = ([a,b,c],[b,a,d],[d,e,c],[a,f,d])

and i sorted it, i would get:

([a,b,c],[a,b,d],[c,d,e],[a,d,f])?

or even:

([a,b,c],[a,b,d],[a,d,f],[c,d,e]) 

if that's easier

Thanx in advance:)

2
  • 2
    Btw. it is a tuple of lists, not vice versa. Commented Dec 12, 2010 at 11:42
  • Which is to say: you do not have tuples in a list here. You have lists in a tuple. [] surround a list. () surround a tuple. Commented Dec 12, 2010 at 17:45

3 Answers 3

6
>>> list01 = (['a','b','c'],['b','a','d'],['d','e','c'],['a','f','d'])
>>> map(sorted, list01)
[['a', 'b', 'c'], ['a', 'b', 'd'], ['c', 'd', 'e'], ['a', 'd', 'f']]
>>> sorted(map(sorted, list01))
[['a', 'b', 'c'], ['a', 'b', 'd'], ['a', 'd', 'f'], ['c', 'd', 'e']]
Sign up to request clarification or add additional context in comments.

Comments

2

Simple as that...

list01 = (['a','b','c'],['b','a','d'],['d','e','c'],['a','f','d'])

print(sorted(map(sorted,list01)))

Comments

2

You can use a generator instead:

>>> list01 = (['a','b','c'],['b','a','d'],['d','e','c'],['a','f','d'])
>>> tuple((sorted(item) for item in list01))
(['a', 'b', 'c'], ['a', 'b', 'd'], ['c', 'd', 'e'], ['a', 'd', 'f'])

Map is faster, btw. ;)

In [48]: timeit tuple(map(sorted, list01))
100000 loops, best of 3: 3.71 us per loop

In [49]: timeit tuple((sorted(item) for item in list01))
100000 loops, best of 3: 7.26 us per loop

Edit: sorting in place is even faster (thanks Karl):

In [120]: timeit [item.sort() for item in list01 if False]
1000000 loops, best of 3: 490 ns per loop

3 Comments

Sorting in place doesn't have to create a new tuple. Even faster in my tests (although it does create a new list, it doesn't populate it): [item.sort() for item in list01 if False] - for about 0.45 us per loop. ;) On my system, the map version is slightly slower and the sorted version is significantly faster, so that there's only about a 40% speed difference there instead of the 95% or so you're reporting.
And, of course, using the ugly if 0 instead of if False shaves off a little bit more, because the name False doesn't have to be looked up. So yeah, that's how you micro-optimize in Python (but if it's that important, why aren't you dropping to C?).
I was just trying to show some examples, it still depends on data. If there are few of them than I'd use the shortest/prettier/most readable one, if there's a lot of them, I'd probably use Cython ;)

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.