python - 使用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]
,它可以应用于字符串或数字。
解决方案
我这样理解你的问题:
我有列表 [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"]
推荐阅读
- json - VSCode - 如何使 JSON 文件实现 TypeScript 接口
- c++ - 使用 Borland C++ Builder 和 Windows API 函数旋转图像
- docker-compose - docker-compose > 气流 > git-sync 错误
- json - 获取“列表”类型的错误
' 不是类型 'Map 的子类型 ' - javascript - Heroku 错误:应用程序发生错误,无法提供您的页面
- python-3.x - 推理模型!!!(一句话的单词重要性)python3
- java - 大写转换——将字符串中每个单词的首字母转换为大写
- javascript - 禁用当前选择,直到在前一个选择中输入某个值
- amazon - 我无法在 Amazon Selling Partner API 的报告中显示我的库存
- c# - Xcode(版本 12.5.1)模拟器没有导航过去我的 Xamarin Forms 应用程序中的某些页面