【问题标题】:Indexing arrays with multiple conditions in Python?在Python中索引具有多个条件的数组?
【发布时间】:2016-05-29 21:42:49
【问题描述】:

是否有一种简单的方法可以访问具有多个条件的数组的内容?

例如,让我们说

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

但我只对 2 到 9(含)范围内的值感兴趣

所以我想知道两件事:

1) 满足这些条件的元素的数量(即 a>1 和 a

2) 具有满足这些条件的值的新数组。在这种情况下,

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

我仍然不擅长用 Python 进行索引:/

【问题讨论】:

  • 使用列表理解。
  • 你可以给排序方法提供你自己的函数来比较两个元素,默认是cmp
  • @PauloScardine 这和sortingz有什么关系?
  • @Barmar 我把这个问题误读为使用多个条件进行排序,而实际上它只是关于过滤。
  • 抱歉,我的措辞可能更好。

标签: python arrays python-2.7 numpy indexing


【解决方案1】:

既然问题被标记为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])

【讨论】:

  • 什么鬼。我知道你可以在 MATLAB 中做到这一点,但在 Python 中却不行。惊人的。如果可以的话,我会投票。编辑:等等,我可以:)
【解决方案2】:

对于一些任意的索引,你可以使用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')

否则你可以编写一个实际的函数以获得额外的灵活性

>>> 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']

无论如何,您应该将逻辑放入函数中,以便于测试和更改

【讨论】:

    【解决方案3】:

    内置过滤器功能就是为此而构建的。

    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)
    

    输出:

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

    【讨论】:

    • 我更喜欢这个答案,使用内置函数
    【解决方案4】:
    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
    

    【讨论】:

    • 我最初也回答了关于切片的问题,但 OP 实际上并不担心索引,所以这个答案是正确的。
    • 可以将条件简化为1 &lt; x &lt; 10
    • 我非常喜欢这个!甚至不知道您可以在这样的括号中使用 if 和 for。谢谢。
    • @JaronThatcher:好吧,既然我看到了,我的回答就没用了。
    • @JohnAlperto 这叫List Comprehension,是 Python 最好的部分之一 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 2016-08-15
    相关资源
    最近更新 更多