或稍微调整一下以获得速度(带有lambda的排序是昂贵的)为了清楚起见,IMO,对=枚举(hist)中的(偏移量,值)的[(值,偏移量)] pairs.sort() indices = [成对(值,偏移)的偏移量] 在Python2.4中允许这样做 还不确定这是件好事。 Andrew da *** @ dalkescientific.com 我假设结果列表应按降序排序 订单。可能最快的方法(因为我们正在调整 速度)只是将对列表comp更改为pairs = [(-value, ) (枚举(hist)]中的(偏移量,值),或者你的Py 2.4键子句 来自key = lambda pair:pair [1] tokey = lambda pair:-pair [1]。 - Paul Howdy, I am using PIL, and would like tomake a list of the pixel valuesin an image, sorted by quantity ofpixels with that value. im.histogram() returns a list whichis a pixel count for each brightness value. So, I want to sort the histogram, and havethe resulting list containthe indexes instead of the counts. This seems like it''d be a fairly commontask, but I don''t know what to callit to look for guidance. Any help is appreciated. Thanks,Kent 解决方案 Assuming im.histogram() returns a list like [ 0, 1, 0, 5, 43, etc. ] howabout: hist = [ 0, 1, 0, 5, 43 ]values = [ i for i in enumerate(hist)]values.sort(lambda a,b: cmp(b[1],a[1]))indexes = [ a for a,b in values ] -- Paul or tweaked a bit for speed (a sort with a lambda is expensive)and for clarity, IMO, pairs = [(value, offset) for (offset, value) in enumerate(hist)]pairs.sort()indexes = [offset for (value, offset) in pairs] In Python2.4 this is allowed Not yet sure that that''s a good thing. Andrew da***@dalkescientific.com or tweaked a bit for speed (a sort with a lambda is expensive) and for clarity, IMO, pairs = [(value, offset) for (offset, value) in enumerate(hist)] pairs.sort() indexes = [offset for (value, offset) in pairs] In Python2.4 this is allowed Not yet sure that that''s a good thing. Andrew da***@dalkescientific.com I assumed that the resulting list should be sorted in descending frequencyorder. Probably the fastest way to do this (since we are tweaking forspeed) would be to just change the pairs list comp to "pairs = [(-value,offset) for (offset, value) in enumerate(hist)]", or your Py 2.4 key clausefrom "key=lambda pair: pair[1]" to "key=lambda pair: -pair[1]". -- Paul 这篇关于列表转换问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 11-03 10:42