我有一个元组:
[('site-nfv01-swsto01',), ('site-nfv01-swsto01V',),('site-nfv01-swsto02',),('site-nfv02-swsto02',), ('site-nfv02-swsto01',) , ('site-nfv02-swsto01V',)]
我想按以下顺序对其进行分类:
site-nfv01-swsto01V
site-nfv01-swsto01
site-nfv01-swsto02
site-nfv02-swsto01V
site-nfv02-swsto01
site-nfv02-swsto02
拥有:[('site-nfv01-swsto01V',), ('site-nfv01-swsto01',),('site-nfv01-swsto02',),('site-nfv02-swsto01V',), ('site-nfv02-swsto01',) , ('site-nfv02-swsto02',)]
574想法是首先按升序对NFV部分进行分类,然后,我们也按升序对SWSTO进行分类,但将以“V”结尾的SWSTO放在第一位
我该怎么做
最好的方法是为
sorted
函数使用key
参数从docs:
要对代码列表进行排序,我将执行以下操作:
如果您不知道lambda表达式是如何工作的,请查看docs
请注意,Python已经对元组进行了自然排序,首先对第一个元素进行排序,然后对第二个元素进行排序,等等。这意味着如果我们可以创建一个反映元素适当排名的元组,那么我们可以简单地使用该元组作为键进行排序
要将排序模式转换为元组,请将“V”的存在视为负无穷大,否则使用数字
最后,我们可以使用Python的便利性,如
zip
和re
来减少代码行或者,对于一行(不要这样做!):
我发现制作一个独立的键控功能更加清晰:
这使您可以非常明确地知道排序键是如何生成的,因为测试起来要容易得多
相关问题 更多 >
编程相关推荐