假设有一个简单的列表,sorted
然后得到以下结果:
s=['university','university','college','school']
sorted(s)
Out[6]: ['college', 'school', 'university', 'university']
sorted
将根据内部编码(utf-8 可能是)对列表进行排序。我想设置自定义编码。在上面的示例中,我想将编码设置为 : ['university','college','school']
。我想根据我的自定义编码进行排序,因此结果应该是sorted(s):['university','university','college','school']
.
我如何在 Python 中实现它?
鉴于您的示例,您可以使用该key
参数传递一个自定义函数,该函数接受一个元素、执行计算并返回要排序的值。
在下面的情况下,每个元素都按order
列表中的索引查找。例如,'college'
returns1
和'university'
returns 0
,所以'university'
在之前排序'college'
。
order=['university','college','school']
s=['school','university','college','university']
print(sorted(s,key=lambda n: order.index(n)))
输出:
['university', 'university', 'college', 'school']
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句