2 回答

TA貢獻1765條經驗 獲得超5個贊
您可以key為max()和指定一個(即 lambda 函數),min()這可以幫助解決此問題。對于你的第一次測試,
lowest_single_dist = min(x, key=lambda i: i["dist"])
返回 中x具有最低值的元素"dist"。如果您想要所有具有該標簽值的元素,您可以使用列表理解:
lowest_dists = [i for i in x if i["dist"] == lowest_single_dist["dist"]]
為了獲得最大的分組,我將首先"tag"在該子集中創建一組可能的值,然后檢查每個有多少個lowest_dists,然后取哪個計數最高:
tags = [i["tag"] for i in lowest_dists] # get a list of just the tags
ct = {t: tags.count(t) for t in set(tags)} # make a dict of tag:count for each unique tag
max_tag = max(ct, key=lambda x: ct[x]) # find the largest count and get the largest tag
r = [i for i in lowest_dists if i["tag"] == max_tag] # use another list comprehension to get all the max tags
如果你想把它全部縮短成兩行,你可以不那么pythonic并這樣做:
m = min(x, key=lambda i: (i["dist"], -1 * max([j["tag"] for j in x if j["dist"] == i["dist"]].count(i["tag"])))
r = [i for i in x if i["tag"] == m["tag"] and i["dist"] == m["dist"]]
這利用了這樣一個事實,即您可以返回一個元組作為排序的鍵,并且只有在第一個值相等時才會檢查元組的第二個值。我將稍微擴展第一行并解釋每個部分的作用:
m = min(x, key=lambda i: (
i["dist"], -1 * max(
[j["tag"] for j in x if j["dist"] == i["dist"]].count(i["tag"])
))
最內層的列表推導式為所有元素生成一個標簽列表,其
x
值為"dist"
asi
然后,取與相同的標簽計數
i
乘以 -1 使其為負數,以便
min()
正確運行創建一個
i["dist"]
和我們剛剛計算的值(i["tag"]
in的頻率x
)的元組,并為每個元素返回該值分配給
m
列表中具有最低值"dist"
和最頻繁值的元素"tag"
分配給具有相同值
r
的元素的子列表和x
"dist"
"tag"
所以基本上與上面相同的過程,但更短,效率更低,并且更復雜一些。

TA貢獻1859條經驗 獲得超6個贊
按“dist”中的值對字典列表進行排序,并取最低值
x.sort(key= lambda x:x['dist'])
lowest = x[0]['dist']
創建一個字典列表,其中 'dist' 的值等于最低值
x2 = [i for i in x if i['dist']==lowest]
這應該是你的答案。如果列表中有多個項目,請重復上述過程。
if len(x2)>1:
x3 = [i['tag'] for i in x2]
mode = max(set(x3), key=x3.count)
r = [i for i in x if i['tag']==mode]
添加回答
舉報