【问题标题】:filtering out strings in a list Python过滤掉列表Python中的字符串
【发布时间】:2022-11-17 03:01:11
【问题描述】:

我是 Python 的新手,我确定我遗漏了一些简单的东西,我想删除所有字符串。

def filter_list(l):
for f in l:
    if isinstance(f, str):
        l.remove(f)
return l

print(filter_list([1,2,'a','b'])) 

我得到的输出是:

[1,2,'b']

【问题讨论】:

    标签: python


    【解决方案1】:

    通常,当我们需要在给定条件的情况下从列表中过滤子列表时,您会很常见地看到这种语法(即列表理解),其作用是做完全相同的事情。看你喜欢哪种风格:

    a = [1,2,'a','b']
    b = [x for x in a if not isinstance(x, str)]
    print(b)  # [1, 2]
    

    【讨论】:

      【解决方案2】:

      您的错误来自迭代中从 list 中删除项目,最后,您不检查最后一项(有关更多详细信息,请阅读:How to remove items from a list while iterating?对于此方法,删除带有 list comprehension 的项目。

      def filter_list(l):
          return [f for f in l if not isinstance(f, str)]
      
      print(filter_list([1,2,'a','b'])) 
      # [1, 2]
      

      【讨论】:

        【解决方案3】:

        所以你可以做类似的事情

        def filter_list(l)
        for f in l:
          if type(f) == str:
            l.remove(f)
        return l
        

        【讨论】:

          猜你喜欢
          • 2015-12-23
          • 1970-01-01
          • 2022-01-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-09-28
          相关资源
          最近更新 更多