简体   繁体   English

如何从python列表中获取值的范围?

[英]how to get a range of values from a list on python?

I'd like to do the following Matlab code: 我想执行以下Matlab代码:

indexes=find(data>0.5);
data2=data(indexes(1):indexes(length(indexes))+1);

in Python, so I did: 在Python中,所以我做到了:

indexes=[x for x in data if x>0.5]
init=indexes[1]
print(indexes)
end=indexes[len(indexes)]+1
data2=data[init:end]

but I'm getting this error: 但我收到此错误:

end=indexes[len(indexes)]+1 IndexError: list index out of range end = indexes [len(indexes)] + 1 IndexError:列表索引超出范围

I think the indexes in Python may not be the same ones as I get in Matlab? 我认为Python中的索引可能与Matlab中的索引不同?

Your list comprehension isn't building a list of indices, but a list of the items themselves. 您的列表理解不是建立索引列表,而是建立项目本身的列表。 You should generate the indices alongside the items using enumerate : 您应该使用enumerate在项目旁边生成索引:

ind = [i for i, x in enumerate(data) if x > 0.5]

And no need to be so verbose with slicing: 切片不必如此冗长:

data2 = data[ind[0]: ind[-1]+1] # Matlab's index 1 is Python's index 0

Indexing the list of indices with len(ind) will give an IndexError as indexing in Python starts from 0 (unlike Matlab) and the last index should be fetched with ind[len(ind)-1] or simply ind[-1] . len(ind)为索引列表建立索引将产生IndexError因为Python中的索引从0开始(与Matlab不同),并且最后一个索引应使用ind[len(ind)-1]或简单的ind[-1]

len(indexes) will give you the index of the last element of the list, so that value plus 1 is out of the range of the list. len(indexes)将为您提供列表最后一个元素的索引,因此值加1不在列表范围内。

It looks like what you're trying to do is find the indices of the list that have values of greater that 0.5 and put those values into data2 . 看来您要尝试执行的操作是找到列表中大于0.5的索引并将这些值放入data2 This is better suited to a numpy array. 这更适合于numpy数组。

import numpy as np
data2 = data[data > 0.5]

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

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