【问题标题】:How do I check that Variable has type List[str]? [duplicate]如何检查变量的类型为 List[str]? [复制]
【发布时间】:2021-11-25 21:49:02
【问题描述】:
x = ['string1','string1','string1']

如何检查x 的类型是否为List[str]

if type(x) != List[str]:
   raise ValueError("x should be list of str")

这个 if 条件返回 Trueraise Error 但不应该。

【问题讨论】:

标签: python if-statement typeerror valueerror


【解决方案1】:

也许

if not (isinstance(x, list) and all(isinstance(item, str) for item in x)):
    raise ValueError

【讨论】:

  • 好吧,我认为有一些解决方案,无需遍历列表中的所有值
  • 不,因为list 不强制它的成员是一种特定类型。不过,您可以创建一个自定义类型来执行此操作
猜你喜欢
  • 2021-11-17
  • 2021-11-02
  • 1970-01-01
  • 1970-01-01
  • 2020-11-25
  • 2011-04-12
  • 2018-03-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多