且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python lambda函数根据字典对列表进行排序

更新时间:2022-06-07 23:27:18

您的第二个代码段的lambda都在同一词典中查找'name',无论它传递了什么对象.那怎么可能呢?

Your second code snippet's lambda looks up 'name' in the same dictionary no matter what object it's passed; how could that possibly work?

您的三分之一似乎都没有试图对流程进行排序;我不确定与该问题有什么关系.

Your third doesn't even seem to be trying to sort the processes; I'm not sure what it has to do with the question.

您将第一个代码段转换为第二个代码段所做的更改显然是由于您担心第一个代码段

The change you've made to turn the first snippet into the second is evidently motivated by your concern that the first

似乎将for语句的局部p变量与p.dict字典混合

seems to mix the local p variable of the for statement with the p.dict dictionary

很乐意为您提供帮助,但恐怕我不明白您看到的是什么问题.也许以下可能有帮助?这里有两个 变量,称为p.第一个用于循环过程;第二个用于循环过程.每次循环时,它的值都是一个过程对象,我们为该过程对象提供一个dict属性,该属性包含'name'的条目.第二个参数是匿名函数(lambda)的参数:其值也始终是一个过程对象.您可以根据需要给它们取不同的名称,它不会破坏任何内容,但实际上我认为它更清楚:在这段代码中,p是您所称的变量,其值是一个过程对象.但是没有什么变得混乱".

and I'd be happy to help but I'm afraid I don't understand what problem it is you see. Perhaps the following may help? There are two variables here called p. The first is used in the loop over processes; each time round the loop its value is a process object, and we give that process object a dict attribute containing an entry for 'name'. The second is the argument to your anonymous function (lambda): its value is also always a process object. You could give them different names if you wanted and it wouldn't break anything, but actually I think it's clearer as it is: in this little bit of code, p is what you call a variable whose value is a process object. But nothing's getting "mixed up".