python - 在列表中映射字典键值
问题描述
假设我有 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]
我怎样才能得到那个输出请提前帮助谢谢
解决方案
>>> 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]
推荐阅读
- flutter - 未找到位于 Scaffold 内的 Material 小部件
- android-mediaplayer - 播放 h.265 文件 android
- session - Symfony5:为功能测试准备会话内容
- css - 在 Gatsby.js 开发模式下使用 PostCSS 时 CSS 不保存
- sql - 优化存储过程
- mysql - 外键可以帮助我,还是我应该考虑一个新的数据库模式?
- amazon-web-services - 是否有适用于 AWS 数据管道的 Azure 集成运行时的等效项?
- javascript - 如何将删除按钮列附加到每个表行
- teamcity - 无论如何要同时更改多个工作目录?
- dataframe - 在 Julia 中检查 Dataframe 多列中的元素