我想检查列表是否仅包含特定元素(在我的情况下为“无”)
我相信有一种Python方式可以做到这一点,我尝试过: if mydict[direction] == None for direction in DIRECTIONS: ...
但这显然行不通
换句话说,我需要一种PYTHONIC方式,可以缩短下一个代码:
def ispure(element)
for direction in DIRECTIONS:
if mydict[direction] != element
return False
else:
pass
return True
希望我很清楚,在此先感谢。
有多种解决方案,因此您可以挑选毒药。假设a
有一个100None
秒的列表,以下是我可以想到的一些列表(按计算机的性能排序):
使用set
:
def only_element(element, ls):
return set(ls) == set([element])
定时:
$ python -m timeit 'set(a) == set([None])'
100000 loops, best of 5: 3.06 µs per loop
使用all
:
def only_element(element, ls):
return all([item == element for item in ls])
定时:
$ python -m timeit 'all([item == None for item in a])'
50000 loops, best of 5: 8.81 usec per loop
使用for
循环:
def only_element(element, ls):
for item in ls:
if item != element:
return False
return True
定时:
$ python -m timeit 'for item in a:\n if item != None:\n break'
100000 loops, best of 5: 9.16 µs per loop
使用filter
:
def only_element(element, ls):
return len(list(filter(lambda x: x != element, ls))) == 0
定时:
$ python -m timeit 'len(list(filter(lambda x: x != None, a))) == 0'
10000 loops, best of 5: 20.8 usec per loop
什么是外卖?
通常,与使用for
循环相比,有一个内置函数可以更好地满足您的需求,并且运行速度更快(并且使用更少的代码)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句