Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中的智能排序_Python_Sorting_Lambda - Fatal编程技术网

python中的智能排序

python中的智能排序,python,sorting,lambda,Python,Sorting,Lambda,我试图对列表中具有混合性质字段的元组进行排序:LABEL.NUMBER。例如: aaaa.143 aadf.23 aaaa.8 .. 因此,我想首先按标签作为字符串进行排序,同时按数字作为数字进行排序,也就是说,排序后应该出现: aaaa.8 aaaa.143 aadf.23 .. 我现在有以下资料: for i in sorted(v_distribution.items(), key=lambda x: x[0]): 使用整个字段作为字符串进行排序,因此我得到: a

我试图对列表中具有混合性质字段的元组进行排序:LABEL.NUMBER。例如:

 aaaa.143
 aadf.23
 aaaa.8
 ..
因此,我想首先按标签作为字符串进行排序,同时按数字作为数字进行排序,也就是说,排序后应该出现:

 aaaa.8
 aaaa.143
 aadf.23
 ..
我现在有以下资料:

for i in sorted(v_distribution.items(), key=lambda x: x[0]): 
使用整个字段作为字符串进行排序,因此我得到:

 aaaa.143
 aaaa.8
 aadf.23
 ..
我应该如何修改lambda函数来执行该任务?

类似于:

>>> s = ['aaaa.143', 'aadf.23', 'aaaa.8']
>>> def key_f(x):
...     head, tail = x.split('.', 1)
...     return (head, int(tail))
...
>>> sorted(s, key=key_f)
['aaaa.8', 'aaaa.143', 'aadf.23']

虽然这可以通过使用lambda来完成,但最好将键计算分离到单独的函数中。

使用lambda可以通过以下方式完成:

for i in sorted(v_distribution.items(), key=lambda x: (x.split('.', 1)[0], int(x.split('.', 1)[1]):

你看到了吗:@JonClements没有,谢谢你的链接,我需要检查解决方案,也许我的问题是重复的…@JonClements原来这里发布的解决方案解决了我的具体任务,而不是你链接中的一般解决方案。所以我认为它不是完全重复的,而是关于类似问题的一个特例。是的,这现在起作用了,结果是非常容易修改,谢谢谢谢你,因为它被标记为lambda,元组有问题,我将接受另一个答案,+1