首页 > 解决方案 > 如何在python的两侧迭代函数?

问题描述

我有一个名为“y”的列表,它由数据表中的最低卡方值组成。所以我的 y 列表看起来像

y = [0.014, 0.048, 3.53, 3.61, 9.08, 12.93, 13.15, 25.03, 26.55, 27.14]

我还有一个名为“chi2”的列表。

在此列表中,我查找 chi2 等于 y[i] 列表中特定值的确切位置。我这样做使用

index_min1 = np.where(chi2 == y[0])
index_min2 = np.where(chi2 == y[1])
index_min3 = np.where(chi2 == y[2])
index_min4 = np.where(chi2 == y[3])
index_min5 = np.where(chi2 == y[4])
index_min6 = np.where(chi2 == y[5])
index_min7 = np.where(chi2 == y[6])
index_min8 = np.where(chi2 == y[7])
index_min9 = np.where(chi2 == y[8])
index_min10 = np.where(chi2 == y[9])

我对python相当陌生,我想知道是否有更好的方法可以迭代每一面,而不是手动输入每一行。

我的思考过程是这样的

import numpy as np                          
import math                                    
from heapq import nsmallest
from numpy import arange


for i in arange(0,9,1):
    index_min+(i+1) = np.where(chi2 == y[i])

这可能是非常错误的,我想知道是否有比手动更好的方法来做到这一点。

标签: pythonnumpy

解决方案


您需要左侧是某种数据结构,支持对其元素进行分配,与y.

例如,使用以下内容调整您的想法list

indices = []

for i in arange(0, 9, 1):
    indices[i] = np.where(chi2 == y[i])

您可以使用“列表理解”进一步简化这一点:

indices = [np.where(chi2 == y[i]) for i in arange(0, 9, 1)]

最后,您实际上并不需要arange,因为您可以迭代y

indices = [np.where(chi2 == y_el) for y_el in y]

如果您更熟悉函数式语言,则等效(仍然有效的 python)形式是:

indices = list(map(lambda e: np.where(chi2 == e), y))

list()(仅当您确实需要将其作为列表时才需要外部。)


推荐阅读