Python:按字典中元组列表中的值对字典列表进行排序

时间:2017-10-10 16:18:44

标签: python list sorting dictionary

我在列表和词典方面遇到了麻烦。我有一份滑雪者词典清单。与下面类似:

skier_1 = {'id': 123,
           'first_name': 'John',
           'last_name': 'Smith',
           'times': [('race_1', 32.25), ('race_2', 33.5), ('race_3', 44)]}

skier_2 = {'id': 234,
           'first_name': 'Allison',
           'last_name': 'Anderson',
           'times': [('race_1', 29.5), ('race_2', 41), ('race_3', 40.25)]}

skier_3 = {'id': 456,
           'first_name': 'Bob',
           'last_name': 'Johnson',
           'times': [('race_1', 31), ('race_2', 41), ('race_3', 39.75)]}

skiers = [skier_1, skier_2, skier_3]

我应该写一个函数来返回n滑雪词典的列表,其中传递的比赛时间最快。如果有一个平局,它应该被滑雪者ID打破。

def fastest_n_times(skiers, race_name, n):

我对如何使用字典skier_x中列表中元组的值对列表进行排序感到困惑。我的计划是完全对列表进行排序,然后返回最高点。我可以很容易地按滑雪者身份排序。

def fastest_n_times(skiers, race_name, n):
   by_id = []
   from operator import itemgetter
   by_id = sorted(skiers, key=itemgetter('id'))

然而,把时间从词典中删除了。我不知道。我试过了:

for skier in skiers:
    fastest_skiers = sorted(skiers, key=itemgetter(sort_key)(itemgetter('assignments')(skier)))

我知道这个循环不是正确的方法。但是,这会返回错误TypeError: 'tuple' object is not callable。我知道元组是不可改变的,但我不知道为什么它不可调用?

def fastest_n_times(skiers, race_name, n):
   fastest_skiers = []
   from operator import itemgetter
   fastest_skiers = sorted(skiers, key=itemgetter('how to get a specific value from a list of tuples'))

有人能指出我正确的方向吗?

谢谢!

编辑:

预期结果应该是这样的:

print(fastest_n_times(skiers, 'race_1', 2))
> [skier_2, skier_3]

print(fastest_n_times(skiers,'race_3', 3))
> [skier_3, skier_2, skier_1]

print(fastest_n_times(skiers, 'race_1', 2))
> [skier_2, skier_1]

print(fastest_n_times(skiers, 'race_2', 3))
> [skier_1, skier_2, skier_3]

print(fastest_n_times(skiers, 'race_1', 1))
> [skier_2]

编辑2: 我现在正在尝试为密钥创建自己的函数。我可以让比赛时间正确,但我不知道如何将它作为关键。我有:

def fastest_n_times(skiers, race_name, n):
    fastest_times = []

    fastest_times = sorted(skiers, key=get_race_key(???, race_name))
    return(fastest_times[:n])

def get_race_key(skier, race_name):
    key_values = []

    key_values = [y for x,y in skier['race_name'] if x == race_name]
    return(key_values[0])

我通常知道它会是这样的:       faster_times = sorted(滑雪者,key = get_race_key)

但我需要将race_name传入正确的时间。

2 个答案:

答案 0 :(得分:0)

为了比较元组,你必须访问时间键的值:

    import collections
    new_dict = collections.OrderedDict()


    skier_1 = {'id':123,
               'first_name':'John',
               'last_name':'Smith',
                'times':[('race_1',32.25),('race_2',33.5),('race_3',44)]}

    skier_2 = {'id':234,
               'first_name':'Allison',
               'last_name':'Anderson',
                'times':[('race_1',29.5),('race_2',41),('race_3',40.25)]}

    skier_3 = {'id':456,
               'first_name':'Bob',
               'last_name':'Johnson',
                'times':[('race_1',31),('race_2',41),('race_3',39.75)]}

    skiers = [skier_1, skier_2, skier_3]
    skiers_names=['skier_1','skier_2','skier_3']

    for i,j in zip(skiers,skiers_names):
        new_dict[j]=i.get('times')




    new=[]

    for i in skiers:
        new.append(i.get('times'))

    race_1=[]
    race_2=[]
    race_3=[]

    for i in new:
        race_1.append(i[0])
        race_2.append(i[1])
        race_3.append(i[2])

    race_1.sort(key=lambda tup: tup[1])  # sorts in place
    race_2.sort(key=lambda tup: tup[1])  # sorts in place
    race_3.sort(key=lambda tup: tup[1])  # sorts in place





    def fastest_n_times(skiers, race_name, n):

        return_list=[]

        for i in race_name[:n]:
            for j,k in new_dict.items():
                if i in k:
                    if j not in return_list:
                        return_list.append(j)

        return return_list

输出:

>> print(fastest_n_times(skiers, race_1, 2))

['skier_2', 'skier_3']

>> print(fastest_n_times(skiers,race_3, 3))

['skier_3', 'skier_2', 'skier_1']

>> print(fastest_n_times(skiers, race_2, 3))

['skier_1', 'skier_2', 'skier_3']

>> print(fastest_n_times(skiers, race_1, 1))

['skier_2']

答案 1 :(得分:0)

要实施 faster_n_times 功能,首先需要为每位滑雪者收集所选比赛的时间,以便按时间排序。

然后,您可以提取 n 最快的滑雪者。

例如:

def fastest_n_times(skiers, selected_race, n):
    time_skier_list = []
    for skier in skiers:
        for race, time in skier['times']:
            if race == selected_race:
                time_skier_list.append((time, skier))
    time_skier_list.sort()
    n_fastest = time_skier_list[:n]
    return [f[1] for f in n_fastest]