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 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:)
>>> 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']]
Simple as that...
list01 = (['a','b','c'],['b','a','d'],['d','e','c'],['a','f','d'])
print(sorted(map(sorted,list01)))
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
精彩评论