简体   繁体   English

在Python中为具有多个条件的数组建立索引?

[英]Indexing arrays with multiple conditions in Python?

Is there a simple way to access the contents of an array with multiple conditions? 有没有一种简单的方法可以在多个条件下访问数组的内容?

For example, lets say 例如,假设

a=[1,2,3,4,5,6,7,8,9,10]

But I'm only interested in values ranging from 2 to 9 (inclusive) 但是我只对2到9(含)范围内的值感兴趣

So I want to know two things: 所以我想知道两件事:

1) The number of elements that satisfy these conditions (that is, where a>1 and a<10), so in this example it would be 8. 1)满足这些条件(即a> 1和a <10)的元素数,因此在此示例中为8。

2) A new array with the values that satify those conditions. 2)具有满足这些条件的值的新数组。 In this case, 在这种情况下,

new_a=[2,3,4,5,6,7,8,9]

I still suck at indexing in Python :/ 我仍然很讨厌在Python中建立索引:/

Python 2.7.10 (default, May 23 2015, 09:44:00) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [1,2,3,4,5,6,7,8,9]
>>> new_a = [x for x in a if x > 1 and x < 10]
>>> print new_a
[2, 3, 4, 5, 6, 7, 8, 9]
>>> print len(new_a)
8

The built in filter function was built for just that. 内置的过滤器功能就是为此而构建的。

def filter_fun(x):
        return 1<x<10
a = range(10)
new_a = filter(filter_fun, a)
print a
print new_a
print len(new_a)

Output: 输出:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7, 8, 9]
8

Since the question is tagged as numpy and array , how about this: 由于该问题被标记为numpyarray ,如何处理:

In [1]: import numpy as np

In [2]: a = np.array([1,2,3,4,5,6,7,8,9,10])

In [3]: a[(a>1) & (a<10)]
Out[3]: array([2, 3, 4, 5, 6, 7, 8, 9])

For some arbitrary indices, you can use itemgetter to build a function 对于某些任意索引,可以使用itemgetter来构建函数

>>> from operator import itemgetter
>>> interesting_things = itemgetter(2, 3, 4, 5, 6, 7, 8, 9)
>>> a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
>>> interesting_things(a)
('c', 'd', 'e', 'f', 'g', 'h', 'i', 'j')

otherwise you can write an actual function for extra flexibility 否则,您可以编写实际的函数以提高灵活性

>>> def interesting_things(L):
...     return [item for i, item in enumerate(L) if 1 < i < 10]
... 
>>> interesting_things(a)
['c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

Regardless, you should put the logic into a function so it's easy to test and change 无论如何,您都应该将逻辑放入函数中,以便于测试和更改

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

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