首页 > 解决方案 > 使用python过滤列表中的任何数字或列表中的任何字符串,而不使用另一个列表

问题描述

我有一个清单,例如:

lst = [1, 2, 'a', 'b']

如果我使用另一个列表,我可以过滤掉数字或字符串。我试图通过检测任何字符串或数字来使函数更加灵活,但我无法找到它的方法。有人可以告诉我解决问题的最佳方法吗?

这是我拥有的代码,它对我有用:

l = [1, 2, 'a', 'b']
def filter_list(l):
  actual_list = [1, 2]
  list_filter = []
  for w in l:
      if w in actual_list:
          list_filter.append(w)     
  return list_filter

我想在不依赖的情况下做同样的事情actual_list = [1, 2],它可以应用于字符串或数字。

标签: python

解决方案


我这样理解你的问题:

我有列表 [1, 2,'a','b'] 并且想要过滤数字或字符串而不中继包含要删除的元素的另一个列表,例如:[x for x in lst if x not in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]

因此,一个可能的答案是:

lst = [1, 2,'a','b', 3.0]

# if you want only the numbers you could check the type of each element
lst_numbers = [x for x in lst if type(x).__name__ == "int" or type(x).__name__ == 'float']

 # if you want only the strings you could check the type of each element
lst_strings = [x for x in lst if type(x).__name__ == "str"]

推荐阅读