【问题标题】:How to pick up all the elements from a python list that meet certain criteria? [duplicate]如何从满足特定条件的python列表中提取所有元素? [复制]
【发布时间】:2017-11-12 02:31:42
【问题描述】:

我有一长串大浮点数:

lis = [0.10593584063824,... ,9.5068763787043226e-34, 9.8763787043226e-34, 8.3617950149494853e-34]

如何将满足特定条件的所有数字放入一个新数组中?例如,我怎样才能将a_constant > .95的所有数字放入一个新列表中

【问题讨论】:

  • 使用过滤器。 a = filter(lambda x: x > 0.95, lis)
  • "...列出所有a_constant > .95" 你这是什么意思? a_constant 是常量还是列表的元素?这非常令人困惑!

标签: python list numpy


【解决方案1】:

使用np.where:

>>> import numpy as np

>>> l = [0.2, 0.4, 0.5]

# Case list into numpy array type.
>>> l_arr = np.array(l)

# Returns the indices that meets the condition.
>>> np.where(l_arr > 0.3)
(array([1, 2]),)

# Returns the values that meets the condition.
>>> l_arr[np.where(l_arr > 0.3)]
array([ 0.4,  0.5])

【讨论】:

    【解决方案2】:

    您可以使用列表推导:

    lis = [0.10593584063824,... ,9.5068763787043226e-34, 9.8763787043226e-34, 8.3617950149494853e-34]
    out = [x for x in lis if 0.65 > x > 0.95]
    

    【讨论】:

    • 是的,但是常数呢?....和x一样吗?
    • 什么常数?
    【解决方案3】:

    如果您在数据科学工作中使用它,我会使用 numpy-。首先,将列表转换为 numpy 数组,然后应用条件并将 numpy 数组转换回列表。

    import numpy as np
    
    lis = [0.10593584063824e-34,2.5068763787043226e-34,9.5068763787043226e-34, 9.8763787043226e-34, 8.3617950149494853e-34]
    
    #Convert the list into a numpy array
    np_array = np.array([[lis]])
    
    #filter the np array and convert back to a list
    new_lis = (np_array[np_array > 3.7e-34]).tolist()
    
    [9.506876378704323e-34, 9.8763787043226e-34, 8.361795014949486e-34]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-03
      • 2016-11-07
      • 1970-01-01
      • 2016-10-24
      • 2011-11-02
      • 1970-01-01
      • 2021-10-02
      • 1970-01-01
      相关资源
      最近更新 更多