简体   繁体   English

如何根据Python中的某些边界提取数组中的元素?

[英]How to extract elements in an array according to some boundaries in Python?

I have an array like x = [3, 5, 6, 11, 18, 24, 29] I want to extract the elements which are greater than 5 and less than or equal to 24 from x.我有一个像 x = [3, 5, 6, 11, 18, 24, 29] 这样的数组我想从 x 中提取大于 5 且小于或等于 24 的元素。

How can i do that?我怎样才能做到这一点?

x = [3, 5, 6, 11, 18, 24, 29]
selected = [i for i in x if i>5 and i<=24]
print(selected)

If you use/prefer numpy, you can use np.where():如果你使用/喜欢 numpy,你可以使用 np.where():

x[np.where((x > 5) & (x <= 24))]

or just:要不就:

x[(x > 5) & (x <= 24)]

result:结果:

array([ 6, 11, 18, 24])

If all you need to do is to extract all the elements/numbers that are greater than 5 and less than 24, you'll have to use for/while loops.如果您需要做的只是提取所有大于 5 且小于 24 的元素/数字,则必须使用 for/while 循环。

for your problem it's best to use a for loop , so the code will look something like this:对于您的问题,最好使用for 循环,因此代码将如下所示:

x = [3, 5, 6, 11, 18, 24, 29]
new_lst = []

for number in x:
    if number > 5 and number < 24:
        new_lst.append(number)

You can read about the .append() function here.您可以在此处阅读有关.append()函数的信息。

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

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