Sort Tuples In Lists In Python
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
Solution 1:
>>> 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']]
Solution 2:
Simple as that...
list01 = (['a','b','c'],['b','a','d'],['d','e','c'],['a','f','d'])
print(sorted(map(sorted,list01)))
Solution 3:
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
Post a Comment for "Sort Tuples In Lists In Python"