2 回答

TA貢獻(xiàn)1765條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以key為max()和指定一個(gè)(即 lambda 函數(shù)),min()這可以幫助解決此問(wèn)題。對(duì)于你的第一次測(cè)試,
lowest_single_dist = min(x, key=lambda i: i["dist"])
返回 中x具有最低值的元素"dist"。如果您想要所有具有該標(biāo)簽值的元素,您可以使用列表理解:
lowest_dists = [i for i in x if i["dist"] == lowest_single_dist["dist"]]
為了獲得最大的分組,我將首先"tag"在該子集中創(chuàng)建一組可能的值,然后檢查每個(gè)有多少個(gè)lowest_dists,然后取哪個(gè)計(jì)數(shù)最高:
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"]]
這利用了這樣一個(gè)事實(shí),即您可以返回一個(gè)元組作為排序的鍵,并且只有在第一個(gè)值相等時(shí)才會(huì)檢查元組的第二個(gè)值。我將稍微擴(kuò)展第一行并解釋每個(gè)部分的作用:
m = min(x, key=lambda i: (
i["dist"], -1 * max(
[j["tag"] for j in x if j["dist"] == i["dist"]].count(i["tag"])
))
最內(nèi)層的列表推導(dǎo)式為所有元素生成一個(gè)標(biāo)簽列表,其
x
值為"dist"
asi
然后,取與相同的標(biāo)簽計(jì)數(shù)
i
乘以 -1 使其為負(fù)數(shù),以便
min()
正確運(yùn)行創(chuàng)建一個(gè)
i["dist"]
和我們剛剛計(jì)算的值(i["tag"]
in的頻率x
)的元組,并為每個(gè)元素返回該值分配給
m
列表中具有最低值"dist"
和最頻繁值的元素"tag"
分配給具有相同值
r
的元素的子列表和x
"dist"
"tag"
所以基本上與上面相同的過(guò)程,但更短,效率更低,并且更復(fù)雜一些。

TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
按“dist”中的值對(duì)字典列表進(jìn)行排序,并取最低值
x.sort(key= lambda x:x['dist'])
lowest = x[0]['dist']
創(chuàng)建一個(gè)字典列表,其中 'dist' 的值等于最低值
x2 = [i for i in x if i['dist']==lowest]
這應(yīng)該是你的答案。如果列表中有多個(gè)項(xiàng)目,請(qǐng)重復(fù)上述過(guò)程。
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]
添加回答
舉報(bào)