0

我有以下元组列表:

items = [
    ('john jones', ['Director', 'Screenwriter', 'Producer']), 
    ('eric smith', ['Screenwriter']), 
    ('anne smith', ['Producer']), 
    ('emily smith', ['Director']), 
    ('steven jones', ['Director', 'Screenwriter'])
]

我需要对其进行排序,以使“导演”出现在“编剧”出现在“制片人”之前。其中的实际订购无关紧要。例如,这将是一个有效的结果:

items = [
    ('john jones', ['Director', 'Screenwriter', 'Producer']), 
    ('emily smith', ['Director']), 
    ('steven jones', ['Director', 'Screenwriter'])
    ('anne smith', ['Producer']), 
    ('eric smith', ['Screenwriter']), 
]

有没有办法做这种排序sorted(items, key=lambda x: ?),还是我必须迭代列表中的每个项目?

4

2 回答 2

3

当然,有一种方法:

$ cat sort.py
order = ['Director', 'Screenwriter', 'Producer']
items = [
    ('john jones', ['Director', 'Screenwriter', 'Producer']), 
    ('eric smith', ['Screenwriter']), 
    ('anne smith', ['Producer']), 
    ('emily smith', ['Director']), 
    ('steven jones', ['Director', 'Screenwriter'])
]

for i in sorted(items, key = lambda x: order.index(x[1][0])):
    print i

让我们尝试一下:

$ python sort.py
('john jones', ['Director', 'Screenwriter', 'Producer'])
('emily smith', ['Director'])
('steven jones', ['Director', 'Screenwriter'])
('eric smith', ['Screenwriter'])
('anne smith', ['Producer'])

当您想按名称对相等的 eintries 进行排序时,您只需要一个元组(Lattyware 的想法):

for i in sorted(items, key = lambda x: (order.index(x[1][0]), x[0])):
    print i
于 2012-06-15T18:45:12.060 回答
0

这是我认为最好的整体解决方案,主要是其他答案的混搭:

import collections

items = collections.OrderedDict([
    ('john jones', ['Director', 'Screenwriter', 'Producer']),
    ('emily smith', ['Director']),
    ('steven jones', ['Director', 'Screenwriter']),
    ('anne smith', ['Producer']),
    ('eric smith', ['Screenwriter']),
])

ordering = {'Director': 1, 'Screenwriter': 2, 'Producer': 3}

def order(item):
    name, values = item
    return ordering.get(values[0], float("inf")), name

print(sorted(items.items(), key=order))

给我们:

[('emily smith', ['Director']), ('john jones', ['Director', 'Screenwriter', 'Producer']), ('steven jones', ['Director', 'Screenwriter']), ('eric smith', ['Screenwriter']), ('anne smith', ['Producer'])]

不在ordering字典中的角色将放在最后。它们将首先按角色排序,然后按名称排序。

这假定子列表是预先排序的。如果没有,很容易先对它们进行排序

于 2012-06-15T19:02:12.433 回答