作者:
demon333 (demon)
2021-03-19 15:15:19各位高手好
小的python苦手這個問題困擾兩天了
想跟大家請教一下
現有
dict1=
{'quiet':[123, 231, 68, 68, 68, 107, 107],
'more': :[3, 3, 82, 82, 146, 146, 95],
...}
想改成為計算每一key中value的次數(頻率)
dict2=
{'quiet':[123:1, 231:1, 68:3, 107:2],
'more': :[3:2, 82:2, 146:2, 95:1],
...}
試過Counter(value)
for key, value in dict1.items():
print(key, Counter(value))
但只會列印出來
卡在不知道怎麼把這個變成dict
請教大家怎麼改寫這一段或者有其他方式完成嗎?謝謝
作者: robert09080 (Aspettarei) 2021-03-19 15:34:00
首先 list.count(x) 可以計算出現次數。那麼以dict1[“quiet”]為範例,只要將 set1=set(dict1[“quiet”]),即可做出unique的dict1[“quiet”],再以for i in set1: dict1[“quiet”].count(i),即可取得出現次數,以你要的型態放置變數裡。