简体   繁体   English

在Python中:如何在嵌套在for循环中的if语句中使用索引号?

[英]In Python: How to use the index number in an if-statement that is nested in a for-loop?

My question is about the fact that I have a simulated dataset, that contains two vectors. 我的问题是关于我有一个包含两个向量的模拟数据集这一事实。 Hence, I have a vector vX and a vector vY. 因此,我有一个向量vX和一个向量vY。 The problem I give is an example that resembles my issues, since my main code is too long. 我的问题是一个与我的问题类似的示例,因为我的主代码太长了。 It is written as a function, as that is what I need in the end. 它被编写为一个函数,因为这最终是我需要的。

The problem at hand is that my vectors are ordered. 当前的问题是我的向量是有序的。 So the element vX[0] should correspond to vY[0], and so on. 因此元素vX [0]应该对应于vY [0],依此类推。 The idea is that I need all the elements of vX that belong in a certain interval, acquire their index number and fill a new vector with the corresponding vY values. 我的想法是,我需要一定间隔内属于vX的所有元素,获取它们的索引号,并用对应的vY值填充一个新向量。

Thus far I have written this: 到目前为止,我已经写了这个:

vX = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
vY = [2, 14, 25, 12, 3, 52 , 5, 10, 7, 19]

vN = []

def(rndf(X, Y)):
    for i in X:
        if i in range(3, 6):
            vN.append(vY[i])
        else:
            vN = vN

vnY = rndf(vX, vY)

In this case the if-statement only holds true for vX = 3, 4 and 5. Then I want to have the corresponding values for vY in the vN vector, ie vN = [25, 12, 3]. 在这种情况下,if语句仅对vX = 3、4和5成立。然后,我想在vN向量中具有vY的相应值,即vN = [25、12、3]。 Hopefully someone understand the problem and is able to help me. 希望有人能理解这个问题并能够为我提供帮助。 Thank you in advance. 先感谢您。

use enumerate 使用enumerate

Ex: 例如:

vX = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
vY = [2, 14, 25, 12, 3, 52 , 5, 10, 7, 19]    

def rndf(X, Y):
    vN = []
    for ind, i in enumerate(X):
        if 3 <= i < 6:                 #better approach as mentioned by FHTMitchell
            vN.append(vY[ind])
    return vN

vnY = rndf(vX, vY)
print( vnY )

Output: 输出:

[25, 12, 3]

With numpy: 使用numpy:

# -*- coding: utf-8 -*-

import numpy as np

vX = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
vY = [2, 14, 25, 12, 3, 52 , 5, 10, 7, 19]

vX = np.asarray(vX)
vy = np.asarray(vY)

vN_ids = np.where((vX >= 3) & (vX <= 6))[0]

vN = vY[vN_ids[0]:vN_ids[-1]]

print (vN)
vX = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
vY = [2, 14, 25, 12, 3, 52 , 5, 10, 7, 19]
vXvY = list(zip(vX, vY))

vn = [x[1] for x in vXvY if x[0] in range(3,6)]
print(vn)

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

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