有没有一种简单的方法来确定变量是列表、字典还是其他什么?
当前回答
使用类型()
x='hello this is a string'
print(type(x))
输出
<class 'str'>
要仅提取str,请使用
x='this is a string'
print(type(x).__name__)#you can use__name__to find class
输出
str
如果使用类型(变量)__name__我们可以读
其他回答
在许多实际情况下,您也可以使用@functools.singledispatch来定义泛型函数(由多个函数组成的函数,对不同类型执行相同的操作),而不是使用类型或isinstance。
换句话说,当您有如下代码时,您可能希望使用它:
def do_something(arg):
if isinstance(arg, int):
... # some code specific to processing integers
if isinstance(arg, str):
... # some code specific to processing strings
if isinstance(arg, list):
... # some code specific to processing lists
... # etc
下面是一个工作原理的小示例:
from functools import singledispatch
@singledispatch
def say_type(arg):
raise NotImplementedError(f"I don't work with {type(arg)}")
@say_type.register
def _(arg: int):
print(f"{arg} is an integer")
@say_type.register
def _(arg: bool):
print(f"{arg} is a boolean")
>>> say_type(0)
0 is an integer
>>> say_type(False)
False is a boolean
>>> say_type(dict())
# long error traceback ending with:
NotImplementedError: I don't work with <class 'dict'>
此外,我们可以使用抽象类同时覆盖几种类型:
from collections.abc import Sequence
@say_type.register
def _(arg: Sequence):
print(f"{arg} is a sequence!")
>>> say_type([0, 1, 2])
[0, 1, 2] is a sequence!
>>> say_type((1, 2, 3))
(1, 2, 3) is a sequence!
使用类型()
x='hello this is a string'
print(type(x))
输出
<class 'str'>
要仅提取str,请使用
x='this is a string'
print(type(x).__name__)#you can use__name__to find class
输出
str
如果使用类型(变量)__name__我们可以读
可以使用type()或isinstance()。
>>> type([]) is list
True
请注意,通过在当前作用域中分配同名变量,可以删除列表或任何其他类型。
>>> the_d = {}
>>> t = lambda x: "aight" if type(x) is dict else "NOPE"
>>> t(the_d) 'aight'
>>> dict = "dude."
>>> t(the_d) 'NOPE'
上面我们看到dict被重新分配给一个字符串,因此测试:
type({}) is dict
…失败。
要解决此问题并更谨慎地使用type():
>>> import __builtin__
>>> the_d = {}
>>> type({}) is dict
True
>>> dict =""
>>> type({}) is dict
False
>>> type({}) is __builtin__.dict
True
value = 12
print(type(value)) # will return <class 'int'> (means integer)
或者你可以这样做
value = 12
print(type(value) == int) # will return true
除了前面的答案之外,值得一提的是collections.abc的存在,它包含几个补充duck类型的抽象基类(abc)。
例如,不必显式检查某项内容是否为列表,而是:
isinstance(my_obj, list)
如果您只想查看所拥有的对象是否允许获取项目,可以使用collections.abc.Sequence:
from collections.abc import Sequence
isinstance(my_obj, Sequence)
如果您对允许获取、设置和删除项目(即可变序列)的对象非常感兴趣,那么您可以选择collections.abc.MutableSequence。
这里还定义了许多其他ABC,可以用作映射的对象的映射、Iterable、Callable等。所有这些的完整列表可以在collections.abc的文档中看到。
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象