我正在尝试编写一个 Python 3 函数来过滤列表和 pop()
所有为字符串的项目。但是当我尝试编写以下函数时:
def filter_list(l):
for i in l:
type_item = type(l[i])
if type_item == "class str":
l.pop(i)
return l
我收到一条错误消息:
File "/home/codewarrior/solution.py", line 3, in filter_list
type_item = type(l[i])
TypeError: list indices must be integers or slices, not str
我相信这个方法的返回值不是 str
,但我没有找到任何文档告诉我如何检查返回是否是字符串。谢谢!
最佳答案
您可以使用列表推导式通过更简单的表达式来完成它。查看以下代码。它将过滤掉初始列表中的所有字符串:
start_list = ["test", 1, 2]
filtered_list = [i for i in start_list if type(i) is not str]
关于python - 如何检查Python中type()方法的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64217770/