0

我有一个多维列表,我想对两个数字元素的组合权重进行排序,例如,结果使用:sorted(results, key=operator.itemgetter(2,3))

[..,1,34]
...
...
[..,10,2]
[..,11,1]
[..,13,3]
[..,13,3]
[..,13,3]
[..,16,1]
[..,29,1]

itemgetter 的问题是首先按元素 2 排序,然后按元素 3 排序,我希望在顶部/底部有 13,3(取决于 asc/desc 排序)。

这是否可能,如果可以,如何。

非常感谢

编辑 1。

对不起,我正在处理 dom 数据,来自搜索页面的结果,可以这么说,它是一个通用的搜索引擎搜索器。

我正在做的是找到 a 和 div 标签,然后我创建一个特定类或 id 出现在 div/a 标签上的项目的计数,这是元素 2,然后我再次重新扫描找到的标签列表,看看是什么标签的其他类/id 与正在处理的当前标签的总数匹配,因此在这种情况下,项目 13,3 有 13 个与该类型标签的类/id 匹配,3 表示还有 3 个其他标签与类/ id 出现的次数相同,因此为什么我希望这样排序,不,它不是字典,它绝对是一个列表。

谢谢你。

4

2 回答 2

2

I'm making a total guess here, given lack of any other explanation, and assuming what you're actually trying to do is sort by the product of the last two keys in your list, secondarily sorted by magnitude of the first element in the product. That's the only explanation I can come up with offhand for why (13,3) would be the top result.

In that case, you'd be looking for something like this:

sorted(results, key=lambda x: (x[-2]*x[-1], x[-2]), reverse=True)

That would give you the following sort:

[[13, 3], [13, 3], [13, 3], [1, 34], [29, 1], [10, 2], [16, 1], [11, 1]]

Alternatively, if what you're actually looking for here is to have the results ordered by the number of times they appear in your list, we can use a collections.Counter. Unfortunately, lists aren't hashable, so we'll cheat a bit and convert them to tuples to use as the keys. There are ways around this, but this is the simplest way for me for now to demonstrate what I'm talking about.

import collections, json
def sort_results(results):
    c = collections.Counter([tuple(k) for k in results])
    return sorted(c, key=lambda x: c[x], reverse=True)

This gets you:

[(13, 3), (1, 34), (16, 1), (29, 1), (11, 1), (10, 2)]

Thanks J.F. Sebastian for pointing out that tuples could be used instead of str!

于 2012-12-26T00:58:06.027 回答
1

Yes, you can write whatever function you want as the key function. For example, if you wanted to sort by the sum of the second and third elements:

def keyfunc(item):
    return sum(operator.itemgetter(2, 3)(item))

sorted(results, key=keyfunc)

So if you used this function as your keyfunc, the item with 13 as the second element 3 as the third element of the list would be sorted as though it were the value 16.

It's not clear how you want to sort these elements, but you can change the body of keyfunc to perform whatever operation you'd like.

于 2012-12-26T00:57:48.030 回答