如何使用python的列表理解来执行下面的matlab代码?

2024-09-24 06:30:51 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,在Matlab中,我有一个一维向量“分数”:

Scores = [3;7;3;2;1;5;1];

我想做的是从所有小于3的元素中减去0.5。在matlab中,我可以做到:

Scores(Scores < 3) = Scores(Scores < 3 ) - 0.5;

然后,我可以使用此结果获得一个布尔向量,该向量表示要删除相应对象的分数的索引:

animals2Delete = animalIDs(Scores < 2)

所以: 如果我的动物名单如下:

animalIDs = [1,2,3,4,5,6,7];

我的matlab代码可以返回:

animals2Delete = [4,5,7]

我的问题是:我能以一种有效的方式使用pythons列表理解吗?或者我需要使用numpy或其他软件包?你知道吗

提前谢谢!你知道吗


Tags: 对象代码元素列表方式向量分数pythons
3条回答

这是可行的,但在我看来,将更容易和清洁与numpy。你知道吗

不带numpy:

Scores = [3, 7, 3, 2, 1, 5, 1]
Scores = [i-0.5 if i<3 else i for i in Scores]

animalIDs = [1, 2, 3, 4, 5, 6, 7] 
animals2Delete = [id for id, score in zip(animalIDs, Scores) if score < 2]
#this could be made in a number of ways, this is just one way.

与numpy逻辑更像是在Matlab中

import numpy as np

Scores = np.array( [3, 7, 3, 2, 1, 5, 1] )
Scores[ Scores < 3 ] = Scores[ Scores < 3 ] - 0.5

animalIDs = np.array( [1, 2, 3, 4, 5, 6, 7] )
animals2Delete = animalIDs[ Scores < 2 ]
#Again, just one way to do it.

似乎所有得分为<;2.5的元素都将被删除。你知道吗

animals2Delete=[]
index=0

for i in Scores:
    if i < 2.5:
        animals2Delete.append(animalIDs[index])
    index+=1

如果我对你的问题理解不正确,请告诉我。你知道吗

假设您使用numpy数组:

import numpy as np
Scores = np.array([3,7,3,2,1,5,1])
animalIDs = np.array([1,2,3,4,5,6,7])

只需创建一个分数小于或等于2的布尔掩码

animals2Delete = Scores <= 2

然后把这个面具贴在动物的身份证上:

animalIDs[animals2Delete]
# returns array([4, 5, 7])

或者一步到位:

animalIDs[Scores <= 2]

这不使用列表理解,而是numpys优化的迭代。结果,至少,应该是你想要的。你知道吗

相关问题 更多 >