我有以下3个功能:
def is_compatible(values):
supported_types = [(str, unicode), (int, long)]
for allowed_types in supported_types:
if isinstance(values[0], allowed_types):
return all(isinstance(item, allowed_types) for item in values)
return False
def is_compatible2(values):
supported_types = [(str, unicode), (int, long)]
for allowed_types in supported_types:
if all(isinstance(item, allowed_types) for item in values):
return True
return False
def is_compatible3(values):
supported_types = [(str, unicode), (int, long)]
return any(
all(isinstance(item, allowed_types) for item in values) for
allowed_types in supported_types
)
有人能给我解释一下,为什么我在timetit中用[1,2,3,4,5]作为arg运行它们,结果是2.47、3.07和3.94?所以第一个是最快的,最后一个是最慢的。我根本看不出这些速度差异的原因。谢谢。你知道吗
你的答案似乎在这里:Why is Python's 'all' function so slow?
在
all
中设置迭代器需要时间。你知道吗在你的第一个函数中,你只做一次。在你的第二个函数中,你偶尔会做两次。所以第一个胜过第二个。你知道吗
你的第二个又因为同样的原因打败了第三个。有更多的开销要设置。围绕
for allowed_types in ...
对any
的调用比简单的for allowed_types in ...
开销更大。你知道吗相关问题 更多 >
编程相关推荐