gpt4 book ai didi

python - Python 中的 "Type comparisons"

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:10:42 24 4
gpt4 key购买 nike

我正在编写一个程序,我必须在其中测试列表的元素是否属于某种类型。列表(z,在下面找到)可以变大,我可以测试标准方式:

for l in z:
typeL = type(l)
if typeL == complex or typeL == float:
#evaluate suite
elif typeL == list:
#evaluate different suite

或者,我可以执行以下操作:

for l in z:
lTemp = l*0
if lTemp == 0:
#evaluate suite
elif lTemp == []:
#evaluate different suite

我的问题是,哪种方法更快、更有效或更受欢迎?在此先感谢大家。

最佳答案

根据 Zen of Python

  • 显式优于隐式。
  • 简单胜于复杂

所以如果你想比较类型,你应该获取类型并比较它们。更清晰的方法是使用接受元组类型参数的 isinstance 方法。所以您的代码可能如下所示:

for l in z:
if isinstance(l,(complex,float)):
#evaluate suite
elif isinstance(l,list):
#evaluate different suite

isinstance 还与 ABC 元类兼容,因此您可以更直接、更明确地进行选择:

from numbers import Number
from collections import Iterable

for l in z:
if isinstance(l,Number):
#evaluate suite
elif isinstance(l,Iterable):
#evaluate different suite

UPD:在回答有关性能的评论中的问题时,您应该记住,premature optimization is the root of all evil .当您的程序运行时,您可以对其进行分析并找出性能实际下降的位置。接下来,您可以在 python 中优化它,在 cython 或 C 中重写,可以使用其他实现,等等。但是当您在 python 中编码时,您必须尊重 python 代码的优点。

关于python - Python 中的 "Type comparisons",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9488608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com