Finding the index of elements based on a condition using python list comprehension

前端 未结 5 2071
谎友^
谎友^ 2020-11-28 02:53

The following Python code appears to be very long winded when coming from a Matlab background

>>> a = [1, 2, 3, 1, 2, 3]
>>> [index for ind         


        
5条回答
  •  醉话见心
    2020-11-28 03:33

    • In Python, you wouldn't use indexes for this at all, but just deal with the values—[value for value in a if value > 2]. Usually dealing with indexes means you're not doing something the best way.

    • If you do need an API similar to Matlab's, you would use numpy, a package for multidimensional arrays and numerical math in Python which is heavily inspired by Matlab. You would be using a numpy array instead of a list.

      >>> import numpy
      >>> a = numpy.array([1, 2, 3, 1, 2, 3])
      >>> a
      array([1, 2, 3, 1, 2, 3])
      >>> numpy.where(a > 2)
      (array([2, 5]),)
      >>> a > 2
      array([False, False,  True, False, False,  True], dtype=bool)
      >>> a[numpy.where(a > 2)]
      array([3, 3])
      >>> a[a > 2]
      array([3, 3])
      

提交回复
热议问题