在Python 2.3中按项目频率对列表列表进行排序 [英] Sorting a list of lists by item frequency in Python 2.3

查看:88
本文介绍了在Python 2.3中按项目频率对列表列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,其中包含类似项的子列表.

I have a list, with sub-lists of items like this.

mylist = [
['ITEM A', 'YES', 'NO', 'YES', 'YES', 'NO', 'NO', 'NO', 'NO', 'NO'],
['ITEM B', 'YES', 'NO', 'YES', 'YES', 'NO', 'NO', 'NO', 'NO', 'MAYBE'],
['ITEM C', 'YES', 'YES', 'YES', 'YES', 'NO', 'NO', 'MAYBE', 'NO', 'MAYBE']
]

现在,我想在这种情况下对子列表进行排序-每行(即子列表)中的项目'YES''MAYBE'越多,则其上移的位置就越高.每行'NO'越多,它在排序列表中的移动就越低.

Now I want to sort the sub lists on this condition — the more each row (i.e. sub list) has the items 'YES' and 'MAYBE', the higher it moves up. The more 'NO's each row has, the lower it moves in the sorting list.

理想的结果是-

mylist = [
['ITEM C', 'YES', 'YES', 'YES', 'YES', 'NO', 'NO', 'MAYBE', 'NO', 'MAYBE'],
['ITEM B', 'YES', 'NO', 'YES', 'YES', 'NO', 'NO', 'NO', 'NO', 'MAYBE'],
['ITEM A', 'YES', 'NO', 'YES', 'YES', 'NO', 'NO', 'NO', 'NO', 'NO']
]
#Item C has 4 'YES' and 2 'MAYBE'
#Item B has 3 'YES' and 1 'MAYBE'
#Item C has 3 'YES'

可悲的是,我被困在 Python 2.3 上,需要找出最有效的方法.

Sadly, I'm stuck on Python 2.3, and need to find out the most efficient way to do this.

推荐答案

一般解决方案:将list.sort与返回元组的键函数一起使用:

General solution: use list.sort with a key function returning a tuple:

mylist.sort(key=lambda sl: (sl.count('YES') + sl.count('MAYBE'), -sl.count('NO')), reverse=True)

keyreverse是在Python 2.4中添加的,因此您必须手动进行操作:

key and reverse were added in Python 2.4, so you'll have to do it manually:

key = lambda sl: (sl.count('YES') + sl.count('MAYBE'), -sl.count('NO'))
mylist.sort(lambda p, q: -cmp(key(p), key(q)))

如果key速度慢,最好使用只对每个项目计算一次key函数的解决方案(所谓的" = Python 2.4已经执行了此优化(或类似操作):

If key is slow it's best to use a solution that computes the key function on each item only once (a so-called "Schwartzian transform"). Note that >=Python 2.4 perform this optimisation (or similar) already:

def key_sort(seq, cmp=None, key=None, reverse=False):
    if key is not None:
        transform = [(key(x), i, x) for i, x in enumerate(seq)]
        transform.sort(None if cmp is None else lambda (k, _, _), (l, _, _): cmp(k, l))
        seq[:] = [x for _, _, x in transform]
    else:
        seq.sort(cmp)
    if reverse:
        seq.reverse()

这篇关于在Python 2.3中按项目频率对列表列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆