简体   繁体   English

根据if条件从python中的列表创建列表

[英]Creating list from list in python based on an if condition

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,其中将仅包含满足条件的标签数组中的索引为3的old_list项。我正在尝试如下操作:

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. 但是我收到以下错误,因为idx是一个数组。 How can i solve this problem? 我怎么解决这个问题?

edited: Idx is an array of equal size with my original data which contains labels for them. 编辑:Idx是与我的原始数据大小相等的数组,其中包含它们的标签。 So basically i want to create a new list which will contain only the items of my original list which eg have the label 3. 因此,基本上我想创建一个新列表,该列表仅包含原始列表中的项目,例如带有标签3。

I want to do something like this: cluster_a = [old_list[x] for x in idx if x == 3] 我想做这样的事情:cluster_a = [old_list [x] for id in x x,如果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. 澄清:我的旧列表是一个包含3d数组的列表,而idx是一个相等大小的数组,其中包含我上面提到的我列表的每个3d数组的标签。 I am trying my best to explain the problem. 我正在尽力解释这个问题。 If something is needed please tell me. 如果需要什么请告诉我。

这是带有3d阵列的列表

这是带有标签的数组

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. 问题不在于idx是一个列表,而是可能x是一个数组old_list必须包含一个列表作为元素。 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]

What about this ? 那这个呢 ? :

new_list = [x for x in old_list if idx.index(x) == 3 ]

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

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