首页 > 解决方案 > 在列表中映射字典键值

问题描述

假设我有 listt=[3 ,3, 4, 0, 0, 3, 1, 0, 4, 3, 3, 3, 0]并且它是子集,因为
t_old=[3, 3, 4, 0, 0]现在我必须计算不在 t_old 中的项目的频率( [3,1, 0, 4, 3, 3, 3, 0]),我已经计算过N={0:2,1:1,3:3,4:1}但之后,我必须将这些值映射到大小为 5 的列表 Nk 中, N={0:2,1:1,3:4,4:1}这样 list 将是NK=[2,1,0,4,1] 0->2,1->1,2->0 (因为没有频率 2),3->3,4->1 所以NK is[2,1,0,4,1] 顺序也很重要 我的代码是

from collections import Counter, defaultdict
import operator


t=[3 ,3, 4, 0, 0, 3, 1, 0, 4, 3, 3, 3, 0]
t_old=[3 ,3, 4, 0, 0]
cluster=5
nr=[]
k=len(t)-len(t_old)
print("Value of k is\n",k)
z=len(t_old)
while(k):
    nr.append(t[z])
    z+=1
    k-=1

print("Value of z is\n",nr)
nr=Counter(nr)  #Counter that calculates the item that are not in t_old
print("counter is\n",nr)
d1 = dict(sorted(nr.items(), key = lambda x:x[0])) #Sorting the nr according to the key
print("Value of sorted dictonary is\n",d1)

所以我想要列表形式的输出

NK is[2,1,0,4,1]

我怎样才能得到那个输出请提前帮助谢谢

标签: pythonlistdictionary

解决方案


>>> from collections import Counter
>>> t=[3 ,3, 4, 0, 0, 3, 1, 0, 4, 3, 3, 3, 0]
>>> t_old=[3, 3, 4, 0, 0]
>>> N = Counter(t) - Counter(t_old)
>>> Nk = [N.get(i,0) for i in range(5)]
>>> Nk
[2, 1, 0, 4, 1]

推荐阅读