简体   繁体   English

Python对数组的列表理解

[英]Python list comprehension over arrays

I have a list of numpy arrays and I'm trying to create a new list with all the elements of the original list, except one. 我有一个numpy数组的列表,我试图用原始列表的所有元素(一个除外)创建一个新列表。 I have the following code: 我有以下代码:

for i in xrange(FOLDS):
    #fold_sample_sets and fold_sample_labels are a list of 10 numpy arrays.
    training_samples = [s for s in fold_sample_sets if fold_sample_sets.index(s) != i]
    training_labels = [l for l in fold_label_sets if fold_label_sets.index(l) != i]

I've tried this with small examples in the interpreter and it's seemed to work. 我已经在解释器中尝试了一些小例子,这似乎很有用。 But here I get the following error: 但是在这里我得到以下错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Any suggestions on how to fix this? 对于如何解决这个问题,有任何的建议吗?

You can use array slicing, 您可以使用数组切片,

for i in range(FOLDS):
    # omit set #i from the list
    training_samples = fold_sample_sets[:i] + fold_sample_sets[i+1:]
    training_labels  = fold_label_sets [:i] + fold_label_sets [i+1:]

In your comprehensions you have: 在您的理解中,您有:

if fold_sample_sets.index(s) != i

The condition for an if has to be True/False. if的条件必须为True / False。 Typically this ValueError is produced when the condition is an array with more than one element. 通常,当条件是具有多个元素的数组时,将产生此ValueError。 For example: 例如:

if np.array([True,False]):
    print(1)

Is this condition True, or is it False? 这个条件是正确的还是错误的? Or is it both? 还是两者? Should it print 1 or not? 是否应该打印1?

The error is suggesting that you use np.any or np.all to reduce the multiple values down to one. 该错误提示您使用np.anynp.all将多个值减小为一个。 The alternative is to make sure that you are not applying the logical operator to a multiple element array. 另一种选择是确保您不将逻辑运算符应用于多元素数组。

What is fold_sample_sets.index(s) != i (for a typical value of s )? fold_sample_sets.index(s) != i是什么(对于s的典型值)?


sets = [np.ones((2,2))*i for i in range(5)]
[s for s in sets if sets.index(s)!=3]  # this error
sets.index(s)   # same error

Looks like list .index does not work with array elements. 看起来list .index不适用于数组元素。 To calculate this index, Python compares s with each element in sets . 为了计算此索引,Python将ssets每个元素进行比较。 When we compare one list with another, [1,2]==[3,4] , we get a simple boolean, False . 当我们将一个列表与另一个列表[1,2]==[3,4] ,我们得到一个简单的布尔值False But when we compare one array with another we get another array: np.array([1,2])==np.array([3,4]) , array([False, False], dtype=bool) . 但是,当我们将一个数组与另一个数组进行比较时,会得到另一个数组: np.array([1,2])==np.array([3,4])array([False, False], dtype=bool) That's where the ambiguity arises. 这就是产生歧义的地方。

A better way of doing the same comprehension (without this .index ) is: 进行相同理解的更好方法(不带此.index )是:

[s for j,s in enumerate(sets) if j!=i]

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

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