使用数组列表中的索引从列表中获取元素

2024-04-18 12:45:23 发布

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

Question:

我有一个数组列表,例如:

a = [array([0, 4]), array([1, 3, 2])]

从另一个变量X,我想取两个子集,它们由a中每个数组中的索引选择

X = [0.1, 0.7, 0.9, 0.2, 0.3] 

我现在想要的是:

result_1 = [0.1, 0.3]
result_2 = [0.7, 0.2, 0.9]

我的解决方案是使用for循环,例如:

def getresult(X, indices):
     result = []
     for i in indices:
          result.append(X[i])
     return result

这很好:

getresult(X, a[0])
[0.1, 0.3]

我以前的编程经验表明,有一种更漂亮、更简单的方法可以做到这一点,而这正是我要问的地方。 最好有人知道一个不需要循环的解决方案。你知道吗

Background/application:

背景:参数优化的交叉验证。你知道吗

我有一个list包含如下数据点

X = [0.1, 0.7, 0.9, 0.2, 0.3]

现在我想重复从列表中取出z个样本(实际上比这个例子要大得多)。因此,我创建了一个新变量:

indices = np.arange(0,len(X),1)

HERE: [0, 1, 2, 3, 4]

然后我洗牌并创建n个样本:

np.random.shuffle(indices)        
nfold_indices = np.array_split(indices,nfolds)

HERE with nfolds = 2: nfold_indices = [array([0, 4]), array([1, 3, 2])]

Tags: 列表forherenp数组result解决方案array
3条回答

return [X[i] for i in indices]就行了。你知道吗

如果来自a的索引不在X中,请使用默认安全的列表理解:

a = [array('i', [0, 4]), array('i', [1, 3, 2])]
X = [0.1, 0.7, 0.9, 0.2, 0.3] 

result = [[(X[i:]+[0])[0] for i in o] for o in a]
#                  ^ default
# [[0.1, 0.3], [0.7, 0.2, 0.9]]

因此,如果您有一个包含超出范围索引的任意数组:

a = [array('i', [0, 4]), array('i', [1, 3, 20])]
#                                           ^ out of range
result = [[(X[i:]+[0])[0] for i in o] for o in a]
# [[0.1, 0.3], [0.7, 0.2, 0]]
#                         ^

你的密码不会被破解

我的第一次尝试,基本上是按照你的方式做事情,更紧凑的方式是:

result1, result2 = [ [X[ii] for ii in array] for array in a]

如果您费心将X转换为numpy数组,可以执行以下操作:

X = np.array([ 0.1,  0.7,  0.9,  0.2,  0.3])
result1, result2 = X[a[0]], X[a[1]]

但这有一个问题,即它不能很好地推广到a中的多个数组中。即使有些人会因为我使用lambda而讨厌我,但另一种可以更好地推广的简洁方法是:

results = map(lambda x: X[x], a)

相关问题 更多 >