【问题标题】:How to check the return value of the type() method in Python? [duplicate]如何在 Python 中检查 type() 方法的返回值? [复制]
【发布时间】:2021-01-20 20:37:15
【问题描述】:

我正在尝试编写一个 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,但是我还没有找到任何文档告诉我如何检查返回是否是一个字符串。谢谢!

【问题讨论】:

  • 如果l是一个列表,那么for i in l中的i代表列表中的每个元素。如果需要使用索引方式,for i in range(len(l)): 则使用type(l[i])
  • @ewong 这行得通!但即使我没有收到任何错误,我仍然没有得到想要的输出。
  • 主要是因为这里提到的另一张海报,你应该试试if isinstance(type_item, str):
  • 这确实不是一个好方法。通常不鼓励使用改变其输入的函数,此外,像这样使用 .pop 效率低下(并且如您所见,容易出错)

标签: python python-3.x string types


【解决方案1】:

您可以使用列表推导式通过更简单的表达式来完成它。查看以下代码。它会从您的初始列表中过滤掉所有字符串:

start_list = ["test", 1, 2]
filtered_list = [i for i in start_list if type(i) is not str]

【讨论】:

  • 他们要求什么和他们需要什么有时是两件不同的事情。我应该记住这一点。
【解决方案2】:

您的type_item 不等于以下字符串:"class str"

相反,您应该这样做: if type_item is str

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-09-03
  • 1970-01-01
  • 1970-01-01
  • 2019-11-14
  • 2021-08-11
  • 2019-03-02
  • 2013-12-16
  • 2021-08-16
相关资源
最近更新 更多