I want to create a new_list which will contain only the items of my old_list which satisfy the condition that the index in an array of labels is 3. I am trying something like this:
new_list = [x for x in old_list if idx[x] == 3]
IndexError: arrays used as indices must be of integer (or boolean) type
But i am getting the following error because idx is an array. How can i solve this problem?
edited: Idx is an array of equal size with my original data which contains labels for them. So basically i want to create a new list which will contain only the items of my original list which e.g have the label 3.
I want to do something like this: cluster_a = [old_list[x] for x in idx if x == 3]
Clarification: my old list is a list containing 3d arrays and the idx is an equal size array containing a label for each 3d array of my list as i aforementioned. I am trying my best to explain the problem. If something is needed please tell me.
This is the list with the 3d arrays
and this is the array with the labels
2 Answers 2
The problem is not that idx is a list but probably that x is an array - old_list must contain a list as an element. You need to reference the index, and not the item itself:
[old_list[x] for x in range(len(old_list)) if idx[x] == 3]
here's a minimal example:
>>> old_list = [4,5,6]
>>> idx = [3,2,3]
>>> [old_list[x] for x in range(len(old_list)) if idx[x] == 3]
[4, 6]
9 Comments
What about this ? :
new_list = [x for x in old_list if idx.index(x) == 3 ]
old_listlooks like?