sort tuples in lists in python

时光总嘲笑我的痴心妄想 提交于 2019-12-11 07:29:09

问题


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:)


回答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']]



回答2:


Simple as that...

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

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



回答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


来源:https://stackoverflow.com/questions/4421410/sort-tuples-in-lists-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!