简体   繁体   English

枚举和映射的使用

[英]Use of enumerate and mapping

newResidues = [1, 2, 3, 4, 5]
newI = [[1,0,1,0,1],[1,1,0,0,0],[1,0,0,1,0]]
newI = np.array(newI)

for i in range(newI.shape[0]):
    indices = [for i,num in enumerate(newI) if num == 1] #line1
    indicesToResidues = dict(zip(indices,newResidues[indices]))#line2

So I know my code is incorrect... this is just an attempt of what I'm trying to do... 所以我知道我的代码不正确...这只是我尝试做的尝试...

in line1 what I'm trying do is make a list of the indices wherever there is a 1 in the matrix for each row, separately. 在line1中,我想做的是分别在矩阵的每一行中有1的地方列出索引。 So indices for the first row of the matrix would look something like [0,2,5] 因此,矩阵第一行的索引类似于[0,2,5]

in line 2 trying to map these indices to a particular value with the same index in a list newResidues. 在第2行中,尝试将这些索引映射到newResidues列表中具有相同索引的特定值。

Any help/comments will be appreciated, thanks! 任何帮助/评论将不胜感激,谢谢!

Replace your loop with the following: 将循环替换为以下内容:

from itertools import compress
for i in newI:
    print map(lambda _: newResidues.index(_), compress(newResidues, i))

itertools.compress is pretty neat and seems perfect for your use case. itertools.compress非常简洁,对于您的用例而言似乎很完美。 After the above gets the values back from compress it finds the index of each value from newResidues -- this won't work correctly if you have duplicate values in newResidues however! 上面的内容从compress取回之后,它会从newResidues找到每个值的索引-但是,如果newResidues有重复的值,这将无法正常工作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM