【问题标题】:Filter from list - Python从列表中过滤 - Python
【发布时间】:2012-09-15 07:37:48
【问题描述】:

我想知道是否有人可以帮助我解决家庭作业问题。

编写一个函数 func(a,x),它接受一个数组 a, x 是两个数字,并返回一个仅包含 a 的值大于或等于 x 的数组

我有

def threshold(a,x):
    for i in a:
        if i>x: print i

但这是错误的方法,因为我没有将它作为数组返回。有人可以提示我正确的方向。提前非常感谢

【问题讨论】:

    标签: python arrays list filter


    【解决方案1】:

    使用list comprehensions:

    [i for i in a if i>x]
    

    【讨论】:

      【解决方案2】:

      使用内置函数filter():

      In [59]: lis=[1,2,3,4,5,6,7]
      In [61]: filter(lambda x:x>=3,lis)  #return only those values which are >=3
      Out[61]: [3, 4, 5, 6, 7]
      

      【讨论】:

      • 谢谢!只是我正在寻找的方法。我还是不明白 lambda 的用法,所以我现在就去阅读它。
      • @user1692517 阅读lambda 很好,但我更喜欢这种情况下的列表理解,它也很容易理解。
      【解决方案3】:

      你可以使用list comprehension:

      def threshold(a, x):
          return [i for i in a if i > x]
      

      【讨论】:

        【解决方案4】:
        def threshold(a,x):
            vals = []
            for i in a:
                if i >= x: vals.append(i)
            return vals
        

        【讨论】:

          【解决方案5】:

          我认为作业问题是实际实现一个过滤器功能。不只是使用内置的。

          def custom_filter(a,x):
              result = []
              for i in a:
                  if i >= x:
                      result.append(i)
              return result
          

          【讨论】:

            猜你喜欢
            • 2011-02-09
            • 2019-08-13
            • 1970-01-01
            • 2010-09-20
            • 2014-02-12
            • 1970-01-01
            • 2015-10-03
            • 2017-08-26
            • 2021-09-17
            相关资源
            最近更新 更多