簡體   English   中英

如何按指定值的平均值對字典列表進行排序

[英]How to sort list of dictionaries by average of specified value

編寫一個名為sort_by_average_rating的函數,它將鍵值存儲列表/數組作為參數,其中每個鍵值存儲具有鍵“ ratings ”、“ budget ”和“ box_office ”,其中“budget”和“box_office”是整數和“ratings”是一個整數列表。

根據“評分”中值的平均值對輸入進行排序。

def sort_by_average_rating(lista):
    lista.sort(sum(lista['ratings']) / int(len(lista['ratings'])))
    return lista

我在輸入時出錯:

輸入錯誤 [{' ratings': [9, 10, 2, 3, 8, 10, 9], 'budget': 16219606.11, 'box_office': 13297812}, {' ratings': [6, 3, 1, 7, 9, 2], 'budget': 12995254.35, 'box_office': 26409035}] 列表索引必須是整數或切片,而不是 str。

預期輸出:

[{'ratings': [6, 3, 1, 7, 9, 2], 'budget': 12995254.35, 'box_office': 26409035}, {'ratings': [9, 10, 2, 3, 8, 10, 9], 'budget': 16219606.11, 'box_office': 13297812}]

我究竟做錯了什么?

您的錯誤消息說您有以下字典列表:

L = [{'ratings': [9, 10, 2, 3, 8, 10, 9], 'budget': 16219606.11, 'box_office': 13297812},
     {'ratings': [6, 3, 1, 7, 9, 2], 'budget': 12995254.35, 'box_office': 26409035}]

您可以只使用sorted與自定義key功能:

res = sorted(L, key=lambda x: sum(x['ratings']) / len(x['ratings']))

[{'box_office': 26409035, 'budget': 12995254.35, 'ratings': [6, 3, 1, 7, 9, 2]},
 {'box_office': 13297812, 'budget': 16219606.11, 'ratings': [9, 10, 2, 3, 8, 10, 9]}]

或者,您可以使用statistics.mean

from statistics import mean

res = sorted(L, key=lambda x: mean(x['ratings']))

請注意, lambda函數采用可迭代 ( L ) 中的每個項目,而不是整個字典列表(如您當前的嘗試)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM