下面是一个使用defaultdict()和bisect()的优化方法:In [14]: lst = [5, 'a', 'x', 3, 6, 'b']
In [15]: from collections import defaultdict
In [16]: import bisect
In [17]: def use_dict_with_bisect(lst):
d = defaultdict(list)
for i in lst:
bisect.insort(d[type(i)], i)
# since bisect doesn't accept key we need to reverse the sorted integers
d[int].sort(reverse=True)
return [d[type(i)].pop() for i in lst]
.....:
演示:
^{pr2}$
如果您处理的是更大的列表,那么使用bisect进行删除会更为优化,它的复杂度大约为O(n2),只需使用python内置的sort()函数,其复杂度为Nlog(n)。在In [26]: def use_dict(lst):
d = defaultdict(list)
for i in lst:
d[type(i)].append(i)
d[int].sort(reverse=True); d[str].sort()
return [d[type(i)].pop() for i in lst]
使用其他答案进行基准测试,显示使用dict和内置sort的最新方法几乎比其他方法快1ms